Init Repo

This commit is contained in:
Gregor Schulte
2021-06-15 11:08:34 +02:00
parent d0b72a118d
commit b303dd00d6
330 changed files with 93268 additions and 0 deletions

View File

@@ -0,0 +1,617 @@
<?php
if (!defined('PICONTROL')) exit();
// functions.php
/**
* Setzt Konfigurationswert für config.ini.php.
*
* <code>$tpl->setConfig('other.test', 'Wert'); // Weißt der Konfigvariable ['other']['test'] den Wert "Wert" zu.</code>
*
* @param string $config Konfigschlüssel
* @param string $value Konfigwert
* @return bool
*/
function setConfig($config, $value, $customFile = NULL)
{
$configPath = CONFIG_PATH;
$configFileSuffix = '.config.ini.php'; // Standard-Konfig
if ($customFile !== NULL)
$configPath = $customFile;
$file = explode(':', $config);
if (count($file) != 2)
return false;
$configFile = $configPath.$file[0].$configFileSuffix;
if (file_exists($configFile) !== true || is_file($configFile) !== true)
return false;
$configArray = parse_ini_file($configFile, true);
if (!strlen($config) > 0 || !is_string($config))
return false;
$var = explode('.', $file[1]);
if (count($var) != 2)
$configArray[$var[0]] = $value;
else
$configArray[$var[0]][$var[1]] = $value;
return writeConfig($configArray, $configFile);
}
/**
* Ermittelt Konfigurationswert aus config.ini.php.
*
* <code>$tpl->getConfig('other.test', 'Wert'); // Ermittelt den Wert von Konfigvariable ['other']['test']. Standardwert: "Wert".</code>
*
* @param string $config Konfigschlüssel
* @param string $default Standardwert
* @return string|int Im Fehlerfall der Standardwert, ansonsten den Konfigwert.
*/
function getConfig($config, $default = NULL, $customFile = NULL)
{
$configPath = CONFIG_PATH;
$configFileSuffix = '.config.ini.php'; // Standard-Konfig
if ($customFile !== NULL)
$configPath = $customFile;
$file = explode(':', $config);
if (count($file) != 1 && count($file) != 2)
return $default;
$configFile = $configPath.$file[0].$configFileSuffix;
if (file_exists($configFile) !== true || is_file($configFile) !== true)
return $default;
$configArray = parse_ini_file($configFile, true);
if (!strlen($config) > 0 || !is_string($config))
return $default;
if (!count($configArray) > 0)
return $default;
if (isset($file[1]))
{
$var = explode('.', $file[1]);
if (count($var) == 1 && isset($configArray[$var[0]]))
return $configArray[$var[0]];
elseif (count($var) == 2 && isset($configArray[$var[0]][$var[1]]))
return $configArray[$var[0]][$var[1]];
}
else
{
if (isset($configArray))
return $configArray;
}
return $default;
}
function removeConfig($config, $customFile = NULL)
{
$configPath = CONFIG_PATH;
$configFileSuffix = '.config.ini.php'; // Standard-Konfig
if ($customFile !== NULL)
$configPath = $customFile;
$file = explode(':', $config);
if (count($file) != 2)
return false;
$configFile = $configPath.$file[0].$configFileSuffix;
if (file_exists($configFile) !== true || is_file($configFile) !== true)
return false;
$configArray = parse_ini_file($configFile, true);
if (!strlen($config) > 0 || !is_string($config))
return false;
$var = explode('.', $file[1]);
if (count($var) == 1)
unset($configArray[$var[0]]);
elseif (count($var) == 2)
unset($configArray[$var[0]][$var[1]]);
else
return false;
return writeConfig($configArray, $configFile);
}
/**
* Schreibt Konfig-Ini-Datei mit neuen Werten.
*
* <code>$tpl->writeConfig();</code>
*
* @return bool
*/
function writeConfig($configArray, $configFile)
{
$res = array(';<?php', ';die();');
ksort($configArray);
foreach ($configArray as $key => $val)
{
if (is_array($val))
{
$res[] = PHP_EOL."[$key]";
foreach ($val as $skey => $sval)
$res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else
$res[] = PHP_EOL."$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
$res[] = ';?>';
if (file_exists($configFile) !== true || is_file($configFile) !== true || is_writeable($configFile) !== true)
return false;
if ($fp = fopen($configFile, 'w'))
{
$startTime = microtime();
do
{
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if (!$canWrite)
usleep(round(rand(0, 100)*1000));
} while ((!$canWrite) && ((microtime()-$startTime) < 1000));
// file was locked so now we can store information
if ($canWrite)
{
fwrite($fp, implode(PHP_EOL, $res));
flock($fp, LOCK_UN);
}
fclose($fp);
}
return true;
}
/**
* Übersetzt Text in andere Sprache.
*
* <code>$tpl->_t('Hallo %s!', 'Welt'); // Rückgabe: Hallo Welt!</code>
*
* @param string $text Text
* @param string|int|float $args[] Argumente
* @return string
*/
function _t()
{
global $globalLanguage, $globalLanguageArray;
$args = func_get_args();
$lang = $globalLanguage;
$langFile = LANGUAGE_PATH.'/'.$lang.'.php';
if (empty($globalLanguageArray) && file_exists($langFile) === true && is_file($langFile) === true)
{
include $langFile;
$globalLanguageArray = $langArray;
}
$checksum = substr(md5($args[0]), 0, 8);
if (is_numeric($checksum))
$checksum[7] = 'z';
if (isset($globalLanguageArray[$checksum]) && $lang != 'de')
$args[0] = $globalLanguageArray[$checksum];
return call_user_func_array('sprintf', $args);
}
/**
* Übersetzt Text in andere Sprache und gibt ihn anschließend aus.
*
* <code>$tpl->_e('Hallo %s!', 'Welt'); // Ausgabe: Hallo Welt!</code>
*
* @param string $text Text
* @param string|int|float $args[] Argumente
* @return bool Ausgabe erfolgt mit "echo".
*/
function _e()
{
global $globalLanguage, $globalLanguageArray;
$args = func_get_args();
$lang = $globalLanguage;
$langFile = LANGUAGE_PATH.'/'.$lang.'.php';
if (empty($globalLanguageArray) && file_exists($langFile) === true && is_file($langFile) === true)
{
include $langFile;
$globalLanguageArray = $langArray;
}
$checksum = substr(md5($args[0]), 0, 8);
if (is_numeric($checksum))
$checksum[7] = 'z';
if (isset($globalLanguageArray[$checksum]) && $lang != 'de')
$args[0] = $globalLanguageArray[$checksum];
echo call_user_func_array('sprintf', $args);
return true;
}
function sizeUnit($size)
{
if ($size == '')
$size = 0;
if ($size < 1024)
return number_format($size, 0, ',', '').' Byte';
elseif ($size < 1024000)
return number_format(round($size/1024,2), 2, ',', '').' KB';
elseif ($size < 1048576000)
return number_format(round($size/1048576,2), 2, ',', '').' MB';
elseif ($size < 1073741824000)
return number_format(round($size/1073741824,2), 2, ',', '').' GB';
}
function return_bytes($size)
{
$size = trim($size);
$last = strtolower($size[strlen($size)-1]);
switch ($last)
{
case 'g':
$size *= 1024;
case 'm':
$size *= 1024;
case 'k':
$size *= 1024;
}
return $size;
}
function numberFormat($value, $precision = 2, $delimiter = ',')
{
return number_format($value, $precision, $delimiter, '');
}
function getFolderSize($folder_path, $folder_size = 0)
{
if (!is_dir($folder_path))
$folder_size += filesize($folder_path);
else
{
$folder_dir = opendir($folder_path);
while ($folder_file = readdir($folder_dir))
{
if (is_file($folder_path.'/'.$folder_file))
$folder_size += filesize($folder_path.'/'.$folder_file);
if (is_dir($folder_path.'/'.$folder_file) && $folder_file != '.' && $folder_file != '..')
$folder_size = getFolderSize($folder_path.'/'.$folder_file, $folder_size);
}
}
return($folder_size);
}
function formatTime($time, $type = 'd.m.Y H:i')
{
if ($time == '')
return false;
return date($type, $time);
}
if (!function_exists('array_column'))
{
function array_column($array, $columnName)
{
return array_map(function($element) use($columnName) { return $element[$columnName]; }, $array);
}
}
function checkUpdate()
{
global $config;
if (!class_exists('cURL'))
(include LIBRARY_PATH.'curl/curl.class.php');
$curl = new cURL($config['url']['update']);
$curl->execute();
if ($curl->getStatusCode() != '200')
return $curl->getStatusCode();
if ($curl->getResult($data) != JSON_ERROR_NONE)
return 1;
if (!isset($data['versions'], $data['latest']))
return 1;
if ($data['latest']['versioncode'] > $config['version']['versioncode'])
{
$currentUpdateKey = array_search($config['version']['versioncode']+1, array_column($data['versions'], 'versioncode'));
return $data['versions'][$currentUpdateKey];
}
else
return 0;
}
function urlIsPublic($url)
{
$ip = gethostbyname($url);
$long = ip2long($ip);
if (($long >= 167772160 && $long <= 184549375) || ($long >= -1408237568 && $long <= -1407188993) || ($long >= -1062731776 && $long <= -1062666241) || ($long >= 2130706432 && $long <= 2147483647) || $long == -1)
return false;
return true;
}
function getDirectory($folder_)
{
$folderArray = array();
$fileArray = array();
$folder = array();
$file = array();
foreach (@scandir($folder_) as $file_)
{
if ($file_[0] != '.')
{
if (is_dir($folder_.'/'.$file_))
{
$folderArray[] = $file_;
$fileArray[] = $file_;
}
}
}
if (isset($folderArray))
foreach ($folderArray as $row)
$folder[] = $row;
if (isset($fileArray))
foreach ($fileArray as $row)
$file[] = $row;
return array ($folder, $file);
}
function getAllFiles($folder_)
{
$folderArray = array();
$fileArray = array();
$folder = array();
$file = array();
$errorArray = array();
foreach (@scandir($folder_) as $file_)
if ($file_[0] != '.')
if (is_dir($folder_.'/'.$file_))
$folderArray[] = $file_;
else
$fileArray[] = $file_;
if (isset($folderArray))
{
foreach ($folderArray as $row)
{
list ($file_return, $error_log) = getAllFiles($folder_.'/'.$row);
$file[$row] = $file_return;
if (is_writeable($folder_.'/'.$row) !== true)
$errorArray[] = $folder_.'/'.$row.'/';
$errorArray = array_merge($errorArray, $error_log);
}
}
if (isset($fileArray))
{
foreach ($fileArray as $row)
{
$file[] = $row;
if (is_writeable($folder_.'/'.$row) !== true)
$errorArray[] = $folder_.'/'.$row;
}
}
return array($file, $errorArray);
}
function delete($folder)
{
chmod($folder, 0777);
if (is_dir($folder))
{
$handle = opendir($folder);
while ($filename = readdir($handle))
if ($filename != '.' && $filename != '..')
delete($folder.'/'.$filename);
closedir($handle);
rmdir($folder);
}
else
unlink($folder);
}
function checkInternetConnection()
{
if (function_exists('fsockopen') && ini_get('allow_url_fopen') !== false)
{
if (!$sock = @fsockopen('www.google.com', 80, $num, $error, 5))
return false; // Raspberry Pi is not connected to internet
else
return true;
}
else
return false;
}
function showHelper($url, $extern = false)
{
global $config;
if ($extern === false)
$url = $config['urls']['helpUrl'].'#'.$url;
return '<a href="'.$url.'" title="Klicke für Hilfe" target="_blank" class="helper">&nbsp;</a>';
}
function array_sort($array, $on, $order = SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0)
{
foreach ($array as $k => $v)
{
if (is_array($v))
{
foreach ($v as $k2 => $v2)
{
if ($k2 == $on)
$sortable_array[$k] = $v2;
}
}
else
$sortable_array[$k] = $v;
}
switch ($order)
{
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v)
$new_array[$k] = $array[$k];
}
return $new_array;
}
function generateUniqId($length = 16, $upper = true)
{
$random1 = rand(1, 1000);
$random2 = rand(1, 1000);
$random3 = rand(1, 1000);
$random11 = 'random'.rand(1, 3);
$random12 = 'random'.rand(1, 3);
$random13 = 'random'.rand(1, 3);
$random = md5($$random11 - $$random12 + $$random13);
$microtime = md5(microtime(true));
$uniqid = substr(md5($random.$microtime.uniqid()), 0, $length);
return ($upper !== true) ? $uniqid : strtoupper($uniqid);
}
function arraySort($array, $on, $order = SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0)
{
foreach ($array as $k => $v)
{
if (is_array($v))
{
foreach ($v as $k2 => $v2)
{
if ($k2 == $on)
$sortable_array[$k] = $v2;
}
}
else
$sortable_array[$k] = $v;
}
switch ($order)
{
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v)
$new_array[$k] = $array[$k];
}
return $new_array;
}
function getTranslatedArrayForJs($translations)
{
if (!is_array($translations))
return false;
$output = array();
foreach ($translations as $translation)
$output[$translation] = _t($translation);
return $output;
}
function getURLLangParam($echo = false, $html = true, $first = false)
{
global $globalLanguage;
$param = '&';
if ($html === true)
$param .= 'amp;';
if ($first !== false)
$param = '?';
$param .= 'lang='.$globalLanguage;
if ($echo !== false)
echo $param;
return $param;
}
?>

View File

@@ -0,0 +1,320 @@
<?php
/**
* A Compatibility library with PHP 5.5's simplified password hashing API.
*
* @author Anthony Ferrara <ircmaxell@php.net>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2012 The Authors
*/
namespace {
if (!defined('PICONTROL')) exit(); // Ausnahme, da namespace
if (!defined('PASSWORD_BCRYPT')) {
/**
* PHPUnit Process isolation caches constants, but not function declarations.
* So we need to check if the constants are defined separately from
* the functions to enable supporting process isolation in userland
* code.
*/
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
define('PASSWORD_BCRYPT_DEFAULT_COST', 10);
}
if (!function_exists('password_hash')) {
/**
* Hash the password using the specified algorithm
*
* @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use
*
* @return string|false The hashed password, or false on error.
*/
function password_hash($password, $algo, array $options = array()) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
}
if (is_null($password) || is_int($password)) {
$password = (string) $password;
}
if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
return null;
}
$resultLength = 0;
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = PASSWORD_BCRYPT_DEFAULT_COST;
if (isset($options['cost'])) {
$cost = (int) $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null;
}
}
// The length of salt to generate
$raw_salt_len = 16;
// The length required in the final serialization
$required_salt_len = 22;
$hash_format = sprintf("$2y$%02d$", $cost);
// The expected length of the final crypt() output
$resultLength = 60;
break;
default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null;
}
$salt_req_encoding = false;
if (isset($options['salt'])) {
switch (gettype($options['salt'])) {
case 'NULL':
case 'boolean':
case 'integer':
case 'double':
case 'string':
$salt = (string) $options['salt'];
break;
case 'object':
if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt'];
break;
}
case 'array':
case 'resource':
default:
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null;
}
if (PasswordCompat\binary\_strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt_req_encoding = true;
}
} else {
$buffer = '';
$buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$strong = false;
$buffer = openssl_random_pseudo_bytes($raw_salt_len, $strong);
if ($buffer && $strong) {
$buffer_valid = true;
}
}
if (!$buffer_valid && @is_readable('/dev/urandom')) {
$file = fopen('/dev/urandom', 'r');
$read = 0;
$local_buffer = '';
while ($read < $raw_salt_len) {
$local_buffer .= fread($file, $raw_salt_len - $read);
$read = PasswordCompat\binary\_strlen($local_buffer);
}
fclose($file);
if ($read >= $raw_salt_len) {
$buffer_valid = true;
}
$buffer = str_pad($buffer, $raw_salt_len, "\0") ^ str_pad($local_buffer, $raw_salt_len, "\0");
}
if (!$buffer_valid || PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) {
$buffer_length = PasswordCompat\binary\_strlen($buffer);
for ($i = 0; $i < $raw_salt_len; $i++) {
if ($i < $buffer_length) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
$salt = $buffer;
$salt_req_encoding = true;
}
if ($salt_req_encoding) {
// encode string with the Base64 variant used by crypt
$base64_digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$bcrypt64_digits =
'./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$base64_string = base64_encode($salt);
$salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits);
}
$salt = PasswordCompat\binary\_substr($salt, 0, $required_salt_len);
$hash = $hash_format . $salt;
$ret = crypt($password, $hash);
if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != $resultLength) {
return false;
}
return $ret;
}
/**
* Get information about the password hash. Returns an array of the information
* that was used to generate the password hash.
*
* array(
* 'algo' => 1,
* 'algoName' => 'bcrypt',
* 'options' => array(
* 'cost' => PASSWORD_BCRYPT_DEFAULT_COST,
* ),
* )
*
* @param string $hash The password hash to extract info from
*
* @return array The array of information about the hash.
*/
function password_get_info($hash) {
$return = array(
'algo' => 0,
'algoName' => 'unknown',
'options' => array(),
);
if (PasswordCompat\binary\_substr($hash, 0, 4) == '$2y$' && PasswordCompat\binary\_strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, "$2y$%d$");
$return['options']['cost'] = $cost;
}
return $return;
}
/**
* Determine if the password hash needs to be rehashed according to the options provided
*
* If the answer is true, after validating the password using password_verify, rehash it.
*
* @param string $hash The hash to test
* @param int $algo The algorithm used for new password hashes
* @param array $options The options array passed to password_hash
*
* @return boolean True if the password needs to be rehashed.
*/
function password_needs_rehash($hash, $algo, array $options = array()) {
$info = password_get_info($hash);
if ($info['algo'] !== (int) $algo) {
return true;
}
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = isset($options['cost']) ? (int) $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST;
if ($cost !== $info['options']['cost']) {
return true;
}
break;
}
return false;
}
/**
* Verify a password against a hash using a timing attack resistant approach
*
* @param string $password The password to verify
* @param string $hash The hash to verify against
*
* @return boolean If the password matches the hash
*/
function password_verify($password, $hash) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;
}
$ret = crypt($password, $hash);
if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret) <= 13) {
return false;
}
$status = 0;
for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i]));
}
return $status === 0;
}
}
}
namespace PasswordCompat\binary {
if (!function_exists('PasswordCompat\\binary\\_strlen')) {
/**
* Count the number of bytes in a string
*
* We cannot simply use strlen() for this, because it might be overwritten by the mbstring extension.
* In this case, strlen() will count the number of *characters* based on the internal encoding. A
* sequence of bytes might be regarded as a single multibyte character.
*
* @param string $binary_string The input string
*
* @internal
* @return int The number of bytes
*/
function _strlen($binary_string) {
if (function_exists('mb_strlen')) {
return mb_strlen($binary_string, '8bit');
}
return strlen($binary_string);
}
/**
* Get a substring based on byte limits
*
* @see _strlen()
*
* @param string $binary_string The input string
* @param int $start
* @param int $length
*
* @internal
* @return string The substring
*/
function _substr($binary_string, $start, $length) {
if (function_exists('mb_substr')) {
return mb_substr($binary_string, $start, $length, '8bit');
}
return substr($binary_string, $start, $length);
}
/**
* Check if current PHP version is compatible with the library
*
* @return boolean the check result
*/
function check() {
static $pass = NULL;
if (is_null($pass)) {
if (function_exists('crypt')) {
$hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
$test = crypt("password", $hash);
$pass = $test == $hash;
} else {
$pass = false;
}
}
return $pass;
}
}
}
?>

View File

@@ -0,0 +1,28 @@
<?php
if (!defined('PICONTROL')) exit();
function rpi_getRuntime()
{
$runtime = trim(@shell_exec('cat /proc/uptime | awk -F \'.\' \'{print $1}\''));
return $runtime;
}
function rpi_getDistribution()
{
$distribution = trim(@shell_exec('cat /etc/issue | cut -d " " -f 1-3'));
if ($distribution == '')
{
$distributionString = @shell_exec('cat /etc/*-release | grep PRETTY_NAME');
preg_match('/.*="([\w\s\d\/]*).*"/i', $distributionString, $match);
if (count($match) == 2)
$distribution = trim($match[1]);
else
$distribution = 'Unknown';
}
return $distribution;
}
?>

View File

@@ -0,0 +1,13 @@
<?php
if (!defined('PICONTROL')) exit();
$site = array(
'install' => 'install.php',
'install_language' => 'install_language.php',
'install_requirement' => 'install_requirement.php',
'install_troubleshooting' => 'install_troubleshooting.php',
'install_user' => 'install_user.php',
'install_cron' => 'install_cron.php',
'install_finish' => 'install_finish.php'
);
?>

View File

@@ -0,0 +1,946 @@
<?php
if (!defined('PICONTROL')) exit();
/**
* Beschreibung. Mehr unter: http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.pkg.html
*/
class FileException extends Exception { }
class PiTpl
{
// Sprache
private $tplLanguage = 'de';
private $tplLanguageFileArray = array();
// Pfade
private $tplFolderPath = 'public_html/templates/';
private $tplFileSuffix = '.tpl.php';
private $tplConfigs = array('main', 'cron');
private $tplConfigSuffix = '.config.ini.php';
private $tplLanguagePath = 'resources/languages/';
private $tplFolderPathPlugin = '';
// Laufzeit
private $runtimeStart = 0;
// Template Variablen
private $tplVariables = array();
// Geladene Elemente
private $tplLoaded = false;
private $tplLoadedHeader = false;
private $tplLoadedFooter = false;
// Lade Elemente?
private $tplLoadHeader = false;
private $tplLoadFooter = false;
// Fehler / Nachrichten
private $ifError = false;
private $tplMsg = array();
private $tpl = NULL;
private $tplConfigArray = array();
public $tplDraw = false;
// Headertitel
private $tplHeaderTitle = '';
private $tplHeaderTitleFormat = '%s | Pi Control';
// Footer
private $tplFooterConfig = array();
// SSH
private $tplSSH = NULL;
function __construct()
{
$this->runtimeStart = microtime(true);
foreach ($this->tplConfigs as $configFile)
{
if (file_exists(CONFIG_PATH.$configFile.$this->tplConfigSuffix) === true && is_file(CONFIG_PATH.$configFile.$this->tplConfigSuffix) === true)
$this->tplConfigArray[$configFile] = parse_ini_file(CONFIG_PATH.$configFile.$this->tplConfigSuffix, true);
}
}
/**
* Übergibt der Klasse die eigene Klassenvariable.
*
* <code>$tpl->setTpl($tpl);</code>
*
* @param class $tpl Klasse
* @return bool
*/
public function setTpl($tpl)
{
$this->tpl = $tpl;
return true;
}
/**
* Setzt Sprache.
*
* <code>$tpl->setLanguage('en'); // Für Englisch.</code>
*
* @param string $lang Sprache
* @return bool
*/
public function setLanguage($lang = 'de')
{
global $globalLanguage;
if (strlen($lang) != 2 || !is_string($lang))
return false;
$this->tplLanguage = $lang;
$globalLanguage = $lang;
return true;
}
/**
* Übersetzt Text in andere Sprache.
*
* <code>$tpl->_t('Hallo %s!', 'Welt'); // Rückgabe: Hallo Welt!</code>
*
* @param string $text Text
* @param string|int|float $args[] Argumente
* @return string
*/
public function _t()
{
$args = func_get_args();
$checksum = substr(md5($args[0]), 0, 8);
if (isset($this->tplLanguageFileArray[$checksum]) && $this->tplLanguage != 'de')
$args[0] = $this->tplLanguageFileArray[$checksum];
return call_user_func_array('sprintf', $args);
}
/**
* Übersetzt Text in andere Sprache und gibt ihn anschließend aus.
*
* <code>$tpl->_e('Hallo %s!', 'Welt'); // Ausgabe: Hallo Welt!</code>
*
* @param string $text Text
* @param string|int|float $args[] Argumente
* @return bool Ausgabe erfolgt mit "echo".
*/
public function _e()
{
$args = func_get_args();
$checksum = substr(md5($args[0]), 0, 8);
if (isset($this->tplLanguageFileArray[$checksum]) && $this->tplLanguage != 'de')
$args[0] = $this->tplLanguageFileArray[$checksum];
echo call_user_func_array('sprintf', $args);
return true;
}
/**
* Setzt Konfigurationswert für config.ini.php.
*
* <code>$tpl->setConfig('other.test', 'Wert'); // Weißt der Konfigvariable ['other']['test'] den Wert "Wert" zu.</code>
*
* @param string $config Konfigschlüssel
* @param string $value Konfigwert
* @return bool
*/
public function setConfig($config, $value, $customFile = NULL)
{
$configPath = CONFIG_PATH;
if ($this->tplFolderPathPlugin != '')
$configPath = $this->tplFolderPathPlugin.'/resources/config/';
if ($customFile !== NULL)
$configPath = $customFile;
$file = explode(':', $config);
if (count($file) != 2)
return false;
$configFile = $configPath.$file[0].$this->tplConfigSuffix;
$md5 = substr(md5($configFile), 0, 6);
if (!isset($this->tplConfigArray[$md5]))
{
if (file_exists($configFile) === true && is_file($configFile) === true)
$this->tplConfigArray[$md5] = parse_ini_file($configFile, true);
else
return false;
}
if (!strlen($config) > 0 || !is_string($config))
return false;
$var = explode('.', $file[1]);
if (count($var) != 2)
return false;
$this->tplConfigArray[$md5][$var[0]][$var[1]] = $value;
return writeConfig($this->tplConfigArray[$md5], $configFile);
}
/**
* Ermittelt Konfigurationswert aus config.ini.php.
*
* <code>$tpl->getConfig('other.test', 'Wert'); // Ermittelt den Wert von Konfigvariable ['other']['test']. Standardwert: "Wert".</code>
*
* @param string $config Konfigschlüssel
* @param string $default Standardwert
* @return string|int Im Fehlerfall der Standardwert, ansonsten den Konfigwert.
*/
public function getConfig($config, $default = NULL, $customFile = NULL)
{
$configPath = CONFIG_PATH;
if ($this->tplFolderPathPlugin != '')
$configPath = $this->tplFolderPathPlugin.'/resources/config/';
if ($customFile !== NULL)
$configPath = $customFile;
$file = explode(':', $config);
if (count($file) != 2)
return $default;
$configFile = $configPath.$file[0].$this->tplConfigSuffix;
$md5 = substr(md5($configFile), 0, 6);
if (!isset($this->tplConfigArray[$md5]))
{
if (file_exists($configFile) === true && is_file($configFile) === true)
$this->tplConfigArray[$md5] = parse_ini_file($configFile, true);
else
return false;
}
if (!strlen($config) > 0 || !is_string($config))
return $default;
if (!count($this->tplConfigArray) > 0)
return $default;
$var = explode('.', $file[1]);
if (count($var) == 1 && isset($this->tplConfigArray[$md5][$var[0]]))
return $this->tplConfigArray[$md5][$var[0]];
elseif (count($var) == 2 && isset($this->tplConfigArray[$md5][$var[0]][$var[1]]))
return $this->tplConfigArray[$md5][$var[0]][$var[1]];
else
return $default;
}
public function removeConfig($config)
{
if (!strlen($config) > 0 || !is_string($config))
return false;
$file = explode(':', $config);
if (count($file) != 2)
return false;
$var = explode('.', $file[1]);
if (count($var) == 1)
unset($this->tplConfigArray[$file[0]][$var[0]]);
elseif (count($var) == 2)
unset($this->tplConfigArray[$file[0]][$var[0]][$var[1]]);
else
return false;
return writeConfig($this->tplConfigArray[$file[0]], CONFIG_PATH.$file[0].$this->tplConfigSuffix);
}
/**
* Übergibt dem TPL-System eine Variable
*
* <code>$tpl->assign('test', 'Wert'); // "test" ist der Name der Variable, "Wert" der Wert.</code>
*
* @param string $name Name der Variable.
* @param string $value Wert der Variable.
* @return bool
*/
public function assign($name, $value = NULL, $merge = false)
{
if (!strlen($name) > 0 || !is_string($name))
return false;
if ($merge === true)
$this->tplVariables[$name] = array_merge((isset($this->tplVariables[$name])) ? $this->tplVariables[$name] : array(), $value);
else
$this->tplVariables[$name] = $value;
return true;
}
/**
* Setzt den Ordner mit den Template-Dateien.
*
* <code>$tpl->setTplFolder('/var/www/public_html/templates'); // Setzt den Pfad auf "/var/www/public_html/templates".</code>
*
* @param string $path Pfad zum Ordner.
* @return bool
*/
public function setTplFolder($path)
{
if (!strlen($path) > 0 || !is_string($path))
return false;
if (file_exists($path) !== true || is_dir($path) !== true)
return false;
$this->tplFolderPath = $path;
return true;
}
/**
* Setzt den Ordner mit den Template-Dateien für Plugins.
*
* <code>$tpl->setTplFolder('/var/www/resources/plugins/test/public_html/templates'); // Setzt den Pfad auf "/var/www/resources/plugins/test/public_html/templates".</code>
*
* @param string $path Pfad zum Ordner.
* @return bool
*/
public function setTplFolderPlugin($path)
{
if (!strlen($path) > 0 || !is_string($path))
return false;
if (file_exists($path) !== true || is_dir($path) !== true)
return false;
$this->tplFolderPathPlugin = $path;
return true;
}
/**
* Setzt den title-Tag.
*
* <code>$tpl->setHeaderTitle('Übersicht');</code>
*
* @param string $title Titel
* @return bool
*/
public function setHeaderTitle($title)
{
if (!strlen($title) > 0 || !is_string($title))
return false;
$this->tplHeaderTitle = $title;
return true;
}
/**
* Setzt das Format für den title-Tag.
*
* <code>$tpl->setHeaderTitleFormat('Pi Control | %s');</code>
*
* @param string $format Format für den Titel.
* @return bool
*/
public function setHeaderTitleFormat($format)
{
if (!strlen($format) > 0 || !is_string($format))
return false;
$this->tplHeaderTitleFormat = $format;
return true;
}
/**
* Setzt den Wert, ob der Header angezeigt werden soll oder nicht.
*
* <code>$tpl->setDrawHeader(true); // Header wird angezeigt.</code>
*
* @param bool $draw
* @return bool
*/
public function setDrawHeader($draw = true)
{
$this->tplLoadHeader = $draw;
return true;
}
/**
* Zeigt Header an.
*
* <code>$tpl->drawHeader();</code>
*
* @return bool
*/
private function drawHeader()
{
if ($this->tplLoadHeader !== true)
return false;
$fileName = CONTENT_PATH.'html_header.php';
$this->tplLoadedHeader = true;
if (file_exists($fileName) !== true || is_file($fileName) !== true)
throw new FileException(self::_t('Datei "%s" existiert nicht oder ist keine g&uuml;ltige Datei.', $fileName));
$tplMain = $this->tpl;
// Übergebe Titel
$data['title'] = sprintf($this->tplHeaderTitleFormat, $this->tplHeaderTitle);
// Uebergebe Uebersetzung
$data['jsTranslations'] = isset($this->tplVariables['jsTranslations']) ? $this->tplVariables['jsTranslations'] : array();
(include_once $fileName) or self::tplError(self::_t('Konnte Datei "%s" nicht &ouml;ffnen und auslesen.', $fileName), __LINE__);
return true;
}
/**
* Setzt den Wert, ob der Footer angezeigt werden soll oder nicht.
*
* <code>$tpl->setDrawFooter(true, $config, $errorHandler); // Footer wird angezeigt.</code>
*
* @param bool $draw
* @param array $mainConfig Konfig-Array aus main_config.php.
* @param array $errorHandler
* @return bool
*/
public function setDrawFooter($draw = true, $mainConfig = NULL)
{
$this->tplLoadFooter = $draw;
$this->tplFooterConfig = $mainConfig;
return true;
}
/**
* Zeigt Footer an.
*
* <code>$tpl->drawFooter();</code>
*
* @return bool
*/
private function drawFooter()
{
global $errorHandler;
if ($this->tplLoadFooter !== true)
return false;
$fileName = CONTENT_PATH.'html_footer.php';
$this->tplLoadedFooter = true;
if (file_exists($fileName) !== true || is_file($fileName) !== true)
throw new FileException(self::_t('Datei "%s" existiert nicht oder ist keine g&uuml;ltige Datei.', $fileName));
$tplMain = $this->tpl;
$tplConfig = $this->tplFooterConfig;
$tplErrorHandler = $errorHandler;
(include_once $fileName) or self::tplError(self::_t('Konnte Datei "%s" nicht &ouml;ffnen und auslesen.', $fileName), __LINE__);
return true;
}
/**
* Öffnet Template-Datei und zeigt Inhalt anschließend an.
*
* <code>$tpl->draw('home'); // Für Home</code>
*
* @param string $tplFileName Template-Datei
* @return bool
*/
public function draw($tplFileName = '')
{
self::drawHeader();
if ($this->ifError === true)
return false;
$this->tplDraw = true;
$folderPath = $this->tplFolderPath;
if ($this->tplFolderPathPlugin != '')
$folderPath = $this->tplFolderPathPlugin.'/public_html/templates/';
if (strlen($tplFileName) >= 1 && is_string($tplFileName))
{
if (file_exists($folderPath.$tplFileName.$this->tplFileSuffix) !== true || is_file($folderPath.$tplFileName.$this->tplFileSuffix) !== true)
return self::tplError(self::_t('Datei "%s" existiert nicht oder ist keine g&uuml;ltige Datei.', $tplFileName), __LINE__-1);
}
self::drawMsg();
$data = $this->tplVariables;
if (strlen($tplFileName) >= 1 && is_string($tplFileName))
(include_once $folderPath.$tplFileName.$this->tplFileSuffix) or self::error(self::_t('Konnte Datei "%s" nicht &ouml;ffnen und auslesen.', $tplFileName), __LINE__);
// Optisch schöner
echo PHP_EOL;
self::drawFooter();
return true;
}
/**
* Öffnet Error-Template-Datei und zeigt Inhalt + Fehler anschließend an
*
* <code>$tpl->drawError('Fehler', 'Nachricht', true); // Für Fehler.</code>
*
* @param string $errorTitle Titel des Fehlers.
* @param string $errorMsg Nachricht des Fehlers.
* @param bool $errorCancel Soll nur die Fehlermeldung angezeigt werden?
* @return bool
*/
private function drawError($errorTitle, $errorMsg, $errorCancel)
{
if (!strlen($errorMsg) > 0 || !is_string($errorMsg))
return false;
if (file_exists($this->tplFolderPath.'error'.$this->tplFileSuffix) !== true || is_file($this->tplFolderPath.'error'.$this->tplFileSuffix) !== true)
return false;
if ($errorCancel === true)
if (self::drawHeader() === false)
return false;
$data['title'] = $errorTitle;
$data['msg'] = $errorMsg;
include $this->tplFolderPath.'error'.$this->tplFileSuffix;
if ($errorCancel === true)
if (self::drawFooter() === false)
return false;
return true;
}
/**
* Fehler anzeigen.
*
* <code>$tpl->error('Fehler', 'Nachricht', true); // Für Fehler.</code>
*
* @param string $errorTitle Titel des Fehlers.
* @param string $errorMsg Nachricht des Fehlers.
* @param bool $errorCancel Soll nur die Fehlermeldung angezeigt werden?
* @return bool
*
* @TODO Wenn $errorCancel auf false steht, wird der Fehler falsch angezeigt.
*/
public function error($errorTitle, $errorMsg, $errorCancel = true)
{
$this->ifError = $errorCancel;
// Prüfe, ob Error-Template-Datei existiert
if (self::drawError($errorTitle, $errorMsg, $errorCancel) === true)
return false;
printf('<h1>%s</h1>%s', $errorTitle, $errorMsg);
return true;
}
/**
* Fehler anzeigen.
*
* <code>$tpl->tplError('Fehler', __LINE__); // Für Fehler.</code>
*
* @param string $errorMsg Nachricht des Fehlers.
* @param int $errorLine Zeilennummer des Fehlers.
* @return bool
*/
private function tplError($errorMsg, $errorLine = 0)
{
self::error('Fehler im TPL-System', sprintf('%s Zeile: %s', $errorMsg, $errorLine), true);
// Rückgabewert für andere Funktion
return false;
}
/**
* Leitet auf eine andere Seite weiter.
*
* <code>$tpl->redirect('?s=overview'); // Leitet auf "?s=overview" weiter.</code>
*
* @param string $url URL auf die weitergeleitet werden soll.
* @return bool
*/
public function redirect($url)
{
if (!strlen($url) > 0 || !is_string($url))
return false;
if (!headers_sent($filename, $linenum))
exit(header('Location: '.$url));
else
{
self::error(self::_t('Weiterleitung'),
'<strong class="red">'.self::_t('Header bereits gesendet. Redirect nicht m&ouml;glich, klicke daher stattdessen <a href="%s">diesen Link</a> an.', $url).'</strong>',
true);
}
return true;
}
/**
* Zeigt Debugmeldungen an.
*
* <code>$tpl->showDebug();</code>
*
* @return bool
*/
public function showDebug()
{
printf(PHP_EOL.'<!-- DEBUG - Start -->'.PHP_EOL.' <hr /><p>Ladezeit: %f<br />Fehler: %s</p>'.PHP_EOL.'<!-- DEBUG - End -->'.PHP_EOL, round(microtime(true)-$this->runtimeStart, 5), ($this->ifError) ? 'true' : 'false');
return true;
}
/**
* Fügt Infomeldung hinzu.
*
* <code>$tpl->msg('red', 'Warnung', 'Infotext', true); // Zeigt rote Warnmeldung an.</code>
*
* @param string $type Type (Farbe) der Meldung. Möglich: red, green, yellow.
* @param string $title Titel der Meldung.
* @param string $msg Nachricht der Meldung.
* @param bool $cancelable Soll die Meldung geschlossen werden können?
* @return bool
*/
public function msg($type, $title = NULL, $msg, $cancelable = true, $id = 0)
{
if (!strlen($type) > 0 || !is_string($type) ||
!strlen($msg) > 0 || !is_string($msg)
)
return false;
if ($id > 0)
{
$this->tplMsg[$id + 100] = array($type, $title, $msg, $cancelable);
}
else
$this->tplMsg[] = array($type, $title, $msg, $cancelable);
return true;
}
public function msgExists($id)
{
if (isset($this->tplMsg[$id + 100]))
return true;
return false;
}
/**
* Zeigt Infomeldung(en) an.
*
* <code>$tpl->drawMsg();</code>
*
* @return bool
*/
private function drawMsg()
{
if (is_array($this->tplMsg) !== true || count($this->tplMsg) == 0)
return false;
if (file_exists($this->tplFolderPath.'msg'.$this->tplFileSuffix) !== true || is_file($this->tplFolderPath.'msg'.$this->tplFileSuffix) !== true)
return false;
foreach ($this->tplMsg as $key => $msg)
{
$data['id'] = $key;
$data['type'] = $msg[0];
$data['title'] = $msg[1];
$data['msg'] = $msg[2];
$data['cancelable'] = $msg[3];
(include $this->tplFolderPath.'msg'.$this->tplFileSuffix) or self::tplError(self::_t('Konnte Datei "%s" nicht öffnen und auslesen.', $this->tplFolderPath.'msg'.$this->tplFileSuffix), __LINE__);
}
return false;
}
/**
* Verbindet sich mit SSH.
*
* <code>$tpl->loadSSH();</code>
*
* @return bool
*/
private function loadSSH()
{
set_include_path(LIBRARY_PATH.'terminal');
if (!class_exists('Net_SSH2'))
{
include(LIBRARY_PATH.'terminal/Net/SSH2.php');
include(LIBRARY_PATH.'terminal/File/ANSI.php');
include(LIBRARY_PATH.'terminal/Crypt/RSA.php');
}
$ssh = NULL;
if (!(isset($_COOKIE['_pi-control_ssh']) && $_COOKIE['_pi-control_ssh'] != ''))
return false;
$token = $_COOKIE['_pi-control_ssh'];
$token2 = $_COOKIE['_pi-control_ssh_'.$token];
$sshType = getConfig('ssh:token_'.$token.'.type', 'password');
$sshPort = getConfig('ssh:token_'.$token.'.port', 22);
$sshUsername = getConfig('ssh:token_'.$token.'.username', 'root');
$sshPassword = getConfig('ssh:token_'.$token.'.password', '');
$sshPrivateKey = base64_decode(getConfig('ssh:token_'.$token.'.privateKey', ''));
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
$sshPassword = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $token2, base64_decode($sshPassword), MCRYPT_MODE_ECB, $iv);
$sshPassword = rtrim($sshPassword, "\0");
$ssh = new Net_SSH2('127.0.0.1', $sshPort);
if ($sshType == 'password')
{
if (!$ssh->login($sshUsername, $sshPassword))
return false;
}
if ($sshType == 'publickey')
{
$sshKey = new Crypt_RSA();
if ($sshPassword != '')
$sshKey->setPassword($sshPassword);
$sshKey->loadKey($sshPrivateKey);
if (!$ssh->login($sshUsername, $sshKey))
return false;
}
if ($ssh === NULL)
return false;
$this->tplSSH = $ssh;
return true;
}
/**
* Führt einen SSH-Befehl aus.
* $canelIfError: 0 = Keine Auswirkung
* 1 = Fehlermeldung
* 2 = Fehlermeldung + Abbrechen
*
* <code>$tpl->executeSSH('ls', true, 0); // Im Fehlerfall wird keine Meldung ausgegeben.</code>
*
* @param string $command SSH-Befehl
* @param bool $blockStream Soll gewartet werden, bis Rückgabe?
* @param int $cancelIfError Verhalten im Fehlerfall.
* @return bool|array
*/
public function executeSSH($command, $blockStream = true, $cancelIfError = 1)
{
if ($this->tplSSH === NULL)
if (self::loadSSH() !== true)
if ($cancelIfError !== 0)
return self::error(_t('SSH-Zugriffsfehler'), _t('Kein SSH-Zugriff, bitte anmelden! <a href="%s">Jetzt anmelden.</a>', '?s=ssh_login'), ($cancelIfError === 1) ? true : false);
if ($this->tplSSH === NULL || ($stream = ssh2_exec($this->tplSSH, $command)) === false)
return false;
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
if ($blockStream === true)
{
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
}
$error = stream_get_contents($errorStream);
$output = stream_get_contents($stream);
return array($error, $output);
}
/**
* Rückgabe der SSH-Ressource.
*
* <code>$tpl->getSSHResource();</code>
*
* @return bool|resource
*/
public function getSSHResource($cancelIfError = 0)
{
if ($this->tplSSH === NULL)
if (self::loadSSH() !== true)
{
if ($cancelIfError !== 0)
self::error(_t('SSH-Zugriffsfehler'), _t('Kein SSH-Zugriff, bitte anmelden! <a href="%s">Jetzt anmelden.</a>', '?s=ssh_login'), ($cancelIfError === 1) ? true : false);
return false;
}
return $this->tplSSH;
}
/**
* Ermittelt Informationen der gespeicherten SSH-Informationen.
*
* <code>$tpl->getSSHInfo();</code>
*
* @return bool|array
*/
public function getSSHInfo()
{
$sshType = getConfig('ssh:latest.type', 'password');
$sshPort = getConfig('ssh:latest.port', 22);
$sshUsername = getConfig('ssh:latest.username', '');
if (isset($_COOKIE['_pi-control_ssh']) && $_COOKIE['_pi-control_ssh'] != '')
{
$token = $_COOKIE['_pi-control_ssh'];
$sshType = getConfig('ssh:token_'.$token.'.type', $sshType);
$sshPort = getConfig('ssh:token_'.$token.'.port', $sshPort);
$sshUsername = getConfig('ssh:token_'.$token.'.username', $sshUsername);
}
return array('type' => $sshType, 'port' => $sshPort, 'username' => $sshUsername);
}
/**
* Setzt SSH-Informationen.
*
* <code>$tpl->setSSHInfo(22, 'pi', 'raspberry', false); // Login nur für aktuelle Sitzung</code>
*
* @param int $port SSH-Port
* @param string $username SSH-Benutzername
* @param string $password SSH-Passwort
* @param bool $saveInFile Langer Login (true) oder nur aktuelle Sitzung (false)?
* @return bool
*/
public function setSSHInfo($type, $port, $username, $password, $privateKey)
{
if (!is_array($SSHInfo = self::getSSHInfo()))
return false;
if ($type != '' && is_string($type))
$SSHInfo['type'] = $type;
if ($port != '' && is_numeric($port))
$SSHInfo['port'] = $port;
if ($username != '' && is_string($username))
$SSHInfo['username'] = $username;
if ($privateKey != '' && is_string($privateKey))
$SSHInfo['privateKey'] = $privateKey;
if ($password != '')
{
if (isset($_COOKIE['_pi-control_ssh']) && $_COOKIE['_pi-control_ssh'] != '')
$this->logoutSSH();
$uniqid = generateUniqId(16, false);
$uniqid2 = generateUniqId(32, false);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
$SSHInfo['password'] = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $uniqid2, $password, MCRYPT_MODE_ECB, $iv));
$SSHInfo['privateKey'] = $privateKey;
if (setConfig('ssh:token_'.$uniqid.'.created', time()) !== true) return false;
if (setConfig('ssh:token_'.$uniqid.'.type', $SSHInfo['type']) !== true) return false;
if (setConfig('ssh:token_'.$uniqid.'.port', $SSHInfo['port']) !== true) return false;
if (setConfig('ssh:token_'.$uniqid.'.username', $SSHInfo['username']) !== true) return false;
if (setConfig('ssh:token_'.$uniqid.'.password', $SSHInfo['password']) !== true) return false;
if (setConfig('ssh:token_'.$uniqid.'.privateKey', base64_encode($SSHInfo['privateKey'])) !== true) return false;
setConfig('ssh:latest.type', $SSHInfo['type']);
setConfig('ssh:latest.port', $SSHInfo['port']);
setConfig('ssh:latest.username', $SSHInfo['username']);
setcookie('_pi-control_ssh', $uniqid, time()+60*60*12);
setcookie('_pi-control_ssh_'.$uniqid, $uniqid2, time()+60*60*12);
$_COOKIE['_pi-control_ssh'] = $uniqid;
$_COOKIE['_pi-control_ssh_'.$uniqid] = $uniqid2;
}
return true;
}
/**
* Löscht SSH-Login.
*
* <code>$tpl->logoutSSH();</code>
*
* @return bool
*/
public function logoutSSH()
{
if (isset($_COOKIE['_pi-control_ssh']) && $_COOKIE['_pi-control_ssh'] != '')
{
$token = $_COOKIE['_pi-control_ssh'];
removeConfig('ssh:token_'.$token);
setcookie('_pi-control_ssh', '', time()-60);
setcookie('_pi-control_ssh_'.$token, '', time()-60);
$_COOKIE['_pi-control_ssh'] = '';
$_COOKIE['_pi-control_ssh_'.$token] = '';
}
return true;
}
}
?>

View File

@@ -0,0 +1,3 @@
<?php
if (!defined('PICONTROL')) exit();
?>