LEPTON CMS 7.0.0
feel free to keep it strictly simple...
Loading...
Searching...
No Matches
C:/Develope/SVN/upload/framework/classes/lepton_handle.php

encrypt fields in a table as an upgrade routine

Parameters
string$table_namefor table_name
array$aListOfFieldsfor aListOfFields
string$field_conditionfor field_condition
LEPTON_handle::encrypt_table($table_name,$aListOfFields,$field_condition);
static encrypt_table(string $table_name='', array $aListOfFields=[], string $field_condition='')
Returns
boolean true if successful

$table_name = 'mod_test'; $aListOfFields = array('name1','name2'); $field_condition = 'test_id'; LEPTON_handle::encrypt_table($table_name,$aListOfFields,$field_condition);

<?php
declare(strict_types=1);
{
const HTACCESS_PATH = SECURE_PATH.'/.htaccess';
const HTPASSWD_PATH = SECURE_PATH.'/.htpasswd';
const ALT_BACKEND_FILE = '/templates/'.DEFAULT_THEME.'/backend/backend/'; // alternative backend file
const ALT_FRONTEND_FILE = '/templates/'.TEMPLATE.'/frontend/'; // alternative frontend file
// [0] class-constants
"&lt;" => "<",
"&gt;" => ">",
"&amp;" => "&",
"&quot;" => "\""
];
static public bool $display_errors = true;
static public function setDisplay(bool $bUseDisplay = true): void
{
self::$display_errors = $bUseDisplay;
}
public function __call(string $name, array $arguments): void
{
$msg = "Unknown class-method: '".$name."'\nParams:\n";
$msg .= LEPTON_tools::display($arguments, "pre");
echo LEPTON_tools::display($msg, "pre", "ui message red");
}
public static function __callStatic(string $name, array $arguments): void
{
$msg = "Unknown static class-method: '".$name."'\nParams:\n";
$msg .= LEPTON_tools::display($arguments, "pre");
echo LEPTON_tools::display($msg, "pre", "ui message red");
}
static public function install_table(string $table_name='', string $table_fields=''): bool
{
if (($table_name == '') || ($table_fields == '')) {
return false;
}
$table = TABLE_PREFIX . $table_name;
$database->simple_query("CREATE TABLE `" . $table . "` (" . $table_fields . ") ");
return true;
}
static public function encrypt_table(string $table_name ='', array $aListOfFields =[], string $field_condition =''): bool
{
if ($table_name == '')
{
return false;
}
if (!is_array($aListOfFields))
{
LEPTON_tools::display("REQUIRED list of names nof table fields must be an array!", "div", "ui red message");
return false;
}
if ( $field_condition == '' ) {
return false;
}
self::create_sik_table($table_name); // keep in mind, that drop_table adds the table_prefix
//get table content
$table_content = array();
$database->execute_query(
"SELECT * FROM ".TABLE_PREFIX.$table_name." ",
true,
$table_content,
true
);
foreach ($table_content as $to_encrypt)
{
$database->secure_build_and_execute('UPDATE', TABLE_PREFIX . $table_name, $to_encrypt, '' . $field_condition . ' =' . $to_encrypt[$field_condition], $aListOfFields);
}
return true;
}
static public function decrypt_table(string $table_name = '', array $aListOfFields = [], string $field_condition = '')
{
if ($table_name == '')
{
return false;
}
if (!is_array($aListOfFields))
{
LEPTON_tools::display("REQUIRED list of names of table-fields must be an array!", "div", "ui red message");
return false;
}
if ($field_condition == '')
{
return false;
}
self::create_sik_table($table_name); // keep in mind, that drop_table adds the table_prefix
//get table content
$table_content = array();
$database->secure_execute_query(
"SELECT * FROM " . TABLE_PREFIX . $table_name . " ",
true,
$table_content,
true,
$aListOfFields
);
foreach ($table_content as $to_decrypt)
{
$result = $database->build_and_execute(
'UPDATE', TABLE_PREFIX.$table_name,
$to_decrypt,
$field_condition.' ='.$to_decrypt[$field_condition]
);
}
return true;
}
static public function insert_values(string $table_name='', string $field_values =''): bool
{
if (($table_name == '') || ($field_values == '')) {
return false;
}
$table = TABLE_PREFIX . $table_name;
$database->simple_query("INSERT INTO `" . $table . "` VALUES " . $field_values . " ");
return true;
}
static public function drop_table(string $table_name=''): bool
{
if ($table_name == '')
{
return false;
}
$table = TABLE_PREFIX . $table_name;
$database->simple_query("DROP TABLE IF EXISTS `" . $table . "` ");
return true;
}
static public function rename_table(string $table_name =''): bool
{
if ($table_name == '')
{
return false;
}
$table_source = TABLE_PREFIX . $table_name;
$table_target = TABLE_PREFIX . 'xsik_' . $table_name;
self::drop_table('xsik_' . $table_name);
$database->simple_query("RENAME TABLE `" . $table_source . "` TO `" . $table_target . "` ");
return true;
}
static public function create_sik_table(string $table_name =''): bool
{
if ($table_name == '')
{
return false;
}
$table_source = TABLE_PREFIX . $table_name;
$table_target = TABLE_PREFIX . 'xsik_' . $table_name;
self::drop_table('xsik_' . $table_name); // keep in mind, that drop_table adds the table_prefix
$database->simple_query("CREATE TABLE `" . $table_target . "` LIKE `" . $table_source . "`");
$database->simple_query("INSERT INTO `" . $table_target . "` SELECT * FROM `" . $table_source . "`");
return true;
}
static public function delete_obsolete_files(string|array ...$aFileNames ): void
{
if (is_string($aFileNames))
{
$aFileNames = [ $aFileNames ];
}
foreach ($aFileNames as $del)
{
if (is_array($del))
{
foreach ($del as $subItem)
{
}
}
else
{
$temp_path = ((!str_contains($del, LEPTON_PATH)) ? LEPTON_PATH : "") . $del;
if (file_exists($temp_path))
{
$result = unlink($temp_path);
if (false === $result)
{
echo "<p>Cannot delete file " . $temp_path . ". Please check file permissions and ownership or delete file manually.</p>";
}
}
}
}
}
static public function delete_obsolete_directories(array $directory_names=[]): void
{
self::register('rm_full_dir');
foreach ($directory_names as $del)
{
$temp_path = LEPTON_PATH . $del;
if (file_exists($temp_path))
{
$result = rm_full_dir($temp_path);
if (false === $result)
{
echo "Cannot delete directory ".$temp_path.". Please check directory permissions and ownership or deleted directories manually.";
}
}
}
}
static public function rename_directories(array $directory_names=[]): void
{
self::register('rename_recursive_dirs');
foreach ($directory_names as $rename)
{
$source_path = LEPTON_PATH . $rename['source'];
$target_path = LEPTON_PATH . $rename['target'];
if (file_exists($source_path))
{
$result = rename_recursive_dirs($source_path, $target_path);
if (false === $result)
{
echo "Cannot rename file ".$source_path.". Please check directory permissions and ownership manually.";
}
}
}
}
static public function include_files(array|string $file_names=[], bool $interrupt=true): void
{
if (is_string($file_names))
{
$file_names = [$file_names];
}
foreach ($file_names as $requestedFile)
{
$temp_path = LEPTON_PATH . $requestedFile;
if (file_exists($temp_path))
{
require_once $temp_path;
} elseif($interrupt === true)
{
"<pre class='ui message'>\nCan't include: ".$temp_path."\n</pre>",
"pre",
"ui message orange"
);
}
}
}
static public function require_alternative(string $file_name, string $usage = 'backend'): bool
{
if (($usage == 'frontend') || ($usage == 'backend'))
{
$temp_path = LEPTON_PATH.(($usage === 'backend') ? self::ALT_BACKEND_FILE : self::ALT_FRONTEND_FILE).$file_name;
if (file_exists($temp_path))
{
require_once $temp_path;
return true;
}
}
return false;
}
static public function install_modules(array $module_names = [] ): void
{
global $module_name, $module_license, $module_author, $module_directory, $module_version, $module_function, $module_description, $module_platform, $module_guid, $lepton_platform;
if (is_string($module_names))
{
$module_names = [$module_names];
}
LEPTON_handle::register('load_module');
foreach ($module_names as $temp_addon)
{
$test = $database->get_one("SELECT `addon_id` FROM `" . TABLE_PREFIX . "addons` WHERE `directory` = '" . $temp_addon . "' ");
if ($test === null)
{
$module_vars = [
'module_license', 'module_author' , 'module_name', 'module_directory',
'module_version', 'module_function', 'module_description',
'module_platform', 'module_guid'
];
foreach ($module_vars as $varname)
{
if (isset(${$varname}))
{
unset(${$varname});
}
}
$temp_path = LEPTON_PATH .'/modules/'.$temp_addon ;
require $temp_path.'/info.php';
load_module( $temp_addon, true );
}
}
}
static public function upgrade_modules(string|array $module_names = []): void
{
if (is_string($module_names))
{
$module_names = array($module_names);
}
LEPTON_handle::register('load_module');
foreach ($module_names as $update)
{
$temp_path = LEPTON_PATH . "/modules/" . $update . "/upgrade.php";
if (file_exists($temp_path))
{
// call upgrade-script direct
require $temp_path;
// update db entries
load_module( $update, false );
// unset module vars
foreach(
[
'module_license', 'module_author' , 'module_name', 'module_directory',
'module_version', 'module_function', 'module_description',
'module_platform', 'module_guid'
] as $varname
)
{
if (isset(${$varname}))
{
unset(${$varname});
}
}
}
}
}
static public function install_droplets(string $module_name='',string|array $zip_names=[]): void
{
droplets::getInstance();
if (is_string($zip_names))
{
$zip_names = array($zip_names);
}
foreach ($zip_names as $to_install)
{
$temp_path = LEPTON_PATH . "/modules/" . $module_name . "/install/".$to_install.".zip";
if (file_exists($temp_path))
{
$result = droplet_install($temp_path, LEPTON_PATH . '/temp/unzip/');
if (count($result['errors']) > 0)
{
die ('ERROR: file is missing: <b> ' . (implode('<br />\n', $result['errors'])) . ' </b>.');
}
}
}
self::delete_obsolete_directories(array("/modules/" . $module_name . "/install"));
}
static public function uninstall_droplets(string|array $droplet_names = []): void
{
if (is_string($droplet_names))
{
$droplet_names = [$droplet_names];
}
foreach ($droplet_names as $to_uninstall)
{
$to_delete = [];
$database->execute_query(
"SELECT `id` FROM ".TABLE_PREFIX."mod_droplets WHERE `name` = '".$to_uninstall."' ",
true,
$to_delete,
false
);
if (isset($to_delete['id']))
{
$database->simple_query("DELETE FROM `" . TABLE_PREFIX . "mod_droplets` WHERE `id` = " . $to_delete['id']);
$database->simple_query("DELETE FROM `" . TABLE_PREFIX . "mod_droplets_permissions` WHERE `id` = " . $to_delete['id']);
}
}
}
static function register(): bool
{
if (0 === func_num_args())
{
return false;
}
$all_args = func_get_args();
foreach($all_args as &$param)
{
if (true === is_array($param))
{
foreach ($param as $ref)
{
}
}
else
{
if (!function_exists($param))
{
$lookUpPath = LEPTON_PATH . "/framework/functions/function." . $param . ".php";
if (file_exists($lookUpPath))
{
require_once $lookUpPath;
}
}
}
}
return true;
}
public static function checkEmailChars(string $sEmail): bool
{
$add_custom = '';
$ini_file_name = LEPTON_PATH."/config/lepton.ini.php";
if (true === file_exists($ini_file_name))
{
$config = parse_ini_string(";" . file_get_contents($ini_file_name), true);
if ($config['custom_vars']['additional_email_chars'] != '')
{
$add_custom = $config['custom_vars']['additional_email_chars'];
}
}
return !((false === filter_var($sEmail, FILTER_VALIDATE_EMAIL)
|| (!preg_match('#^[' .LEPTON_core::getInstance()->email_chars.$add_custom.']+$#', $sEmail))));
}
public static function checkPasswordChars(string $sPassword): bool
{
$add_custom = '';
$ini_file_name = LEPTON_PATH . "/config/lepton.ini.php";
if (true === file_exists($ini_file_name))
{
$config = parse_ini_string(";" . file_get_contents($ini_file_name), true);
if ($config['custom_vars']['additional_password_chars'] != '')
{
$add_custom = $config['custom_vars']['additional_password_chars'];
}
}
return !((false === !preg_match('/[^'.LEPTON_core::getInstance()->password_chars.$add_custom.']/', $sPassword)));
}
public static function checkUsernameChars(string $sName): bool
{
$add_custom = '';
$ini_file_name = LEPTON_PATH . "/config/lepton.ini.php";
if (true === file_exists($ini_file_name))
{
$config = parse_ini_string(";" . file_get_contents($ini_file_name), true);
if ($config['custom_vars']['additional_usernames_chars'] != '')
{
$add_custom = $config['custom_vars']['additional_usernames_chars'];
}
}
return !!preg_match("#^[" . LEPTON_core::getInstance()->username_chars . $add_custom . "]+$#", $sName);
}
public static function checkHexChars(string $sHexHash): bool
{
return !!preg_match("~^[".LEPTON_core::getInstance()->hex_chars."]+$~", $sHexHash);
}
public static function restoreSpecialChars(string &$sAnyString, array $aAnyAssocArray = self::SPECIAL_CHARS_RESTORE): void
{
$aLookUp = array_keys($aAnyAssocArray);
$aReplace = array_values($aAnyAssocArray);
$sAnyString = str_replace( $aLookUp, $aReplace, $sAnyString );
}
public static function restoreStandardProtection() : bool
{
if (file_exists(self::HTACCESS_PATH))
{
unlink(self::HTACCESS_PATH);
unlink(self::HTPASSWD_PATH);
}
$admin_username = LEPTON_database::getInstance()->get_one("SELECT username FROM " . TABLE_PREFIX . "users WHERE user_id = 1 ");
$htuser = $admin_username;
$random_value = random_int(100000,999999);
$htpassword = password_hash((string)$random_value, PASSWORD_DEFAULT );
$htcontent = "# .htaccess-Datei
AuthType Basic
AuthName 'Protected area - Please insert password!'
AuthUserFile ".self::HTPASSWD_PATH."
require user ".$htuser."
";
$htpwcontent = "# Password file, user:".$htuser.", password: ".$random_value."
".$htuser.":".$htpassword."
";
file_put_contents(self::HTACCESS_PATH,$htcontent);
file_put_contents(self::HTPASSWD_PATH,$htpwcontent);
return true;
}
public static function createStandardProtection(string $path = '/temp/secure/', string $username = ''): bool
{
if($username == '')
{
echo LEPTON_tools::display('USERNAME is mandantory as second parameter in this method', 'pre', 'ui red message');
return false;
}
if (file_exists(LEPTON_PATH . $path . '/.htaccess'))
{
unlink(LEPTON_PATH.$path.'/.htaccess');
unlink(LEPTON_PATH.$path.'/.htpasswd');
}
$htuser = $username;
$random_value = random_int(100000,999999);
$htpassword = password_hash((string)$random_value, PASSWORD_DEFAULT );
$htcontent = "# .htaccess-Datei
AuthType Basic
AuthName 'Protected area - Please insert password!'
AuthUserFile ".LEPTON_PATH.$path."/.htpasswd
require user ".$htuser."
";
$htpwcontent = "# Password file, user:".$htuser.", password: ".$random_value."
".$htuser.":".$htpassword."
";
file_put_contents(LEPTON_PATH . $path . '/.htaccess', $htcontent);
file_put_contents(LEPTON_PATH . $path . '/.htpasswd', $htpwcontent);
return true;
}
static function array_orderby(array $array, string $on, string $order = SORT_ASC): array
{
$new_array = [];
$sortable_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;
default:
LEPTON_tools::display(__CLASS__." [10023] No order match!", "pre", "ui message red");
break;
}
foreach ($sortable_array as $k => $v)
{
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
// [5.4.1]
static public function themeExists(string $sThemeName = ""): bool
{
$result = LEPTON_database::getInstance()->get_one("SELECT `directory` FROM `".TABLE_PREFIX."addons` WHERE `directory` ='".$sThemeName."'");
return ($result !== NULL);
}
static public function moveThemeFiles(string $sModuleDirectory = ""): void
{
$sSingleModuleDirectory = self::getModuleDirectory($sModuleDirectory);
// get all themes
$aAllThemes = self::getAllThemes();
foreach ($aAllThemes as $sForTheme)
{
$sBaseSourcePath = LEPTON_PATH . "/modules/" . $sSingleModuleDirectory . "/backendthemes/" . $sForTheme;
$sTargetPath = LEPTON_PATH . "/templates/" . $sForTheme . "/backend/" . $sSingleModuleDirectory;
if (true === file_exists($sBaseSourcePath))
{
self::copyThemeFilesRecursive($sBaseSourcePath, $sTargetPath);
}
}
}
// [5.4.3] Internal
static public function copyThemeFilesRecursive(string $dirsource, string $dirdest, int $deep = 0): bool
{
if (true === is_dir($dirsource))
{
if(($deep === 0) && (false === is_dir($dirdest)))
{
LEPTON_core::make_dir($dirdest);
}
$dir= dir($dirsource);
while ( $file = $dir->read() )
{
if( $file[0] === "." )
{
continue;
}
if( !is_dir($dirsource."/".$file) )
{
copy($dirsource . "/" . $file, $dirdest . "/" . $file);
LEPTON_core::change_mode($dirdest . "/" . $file);
} else {
LEPTON_core::make_dir($dirdest . "/" . $file);
self::copyThemeFilesRecursive($dirsource . "/" . $file, $dirdest . '/' . $file, $deep + 1);
}
}
$dir->close();
}
if ($deep == 0)
{
// Is this a working copy? If not ... we try to remove the unneeded files here
if (!file_exists(dirname($dirsource, 2) . "/.git"))
{
LEPTON_handle::register("rm_full_dir");
rm_full_dir( $dirsource );
}
}
return true;
}
// [5.4.4] Deletes all "theme" specific files of a given module from all installed themes.
static public function removeAllThemeFiles(string $sModuleDirectory = ""): void
{
$sSingleModuleDirectory = self::getModuleDirectory($sModuleDirectory);
$aAllThemes = self::getAllThemes();
foreach ($aAllThemes as $aTempThemeDirectory)
{
self::delete_obsolete_directories(["/templates/" . $aTempThemeDirectory . "/backend/" . $sSingleModuleDirectory]);
}
}
// [5.4.5] Try to get the module directory
static public function getModuleDirectory(string $anyNameOrPath = ""): string
{
if (empty($anyNameOrPath))
{
return "";
}
$backtrace = debug_backtrace();
$aTempTest = [""];
if (isset($backtrace[1]['file']))
{
$aTempTest = self::getPathElements($backtrace[1]['file']);
}
// [5.4.5.3] try to extract the module directory
$aTemp = self::getPathElements($anyNameOrPath);
return ($aTemp[0] === $aTempTest[0]) ? $aTemp[0] : "";
}
// [5.4.6] Internal
static public function getAllThemes(): array
{
$aAllThemes = [];
LEPTON_database::getInstance()->execute_query(
"SELECT `directory` FROM `" . TABLE_PREFIX . "addons` WHERE `function` = 'theme'",
true,
$aAllThemes,
true
);
$aReturnValues = [];
foreach($aAllThemes as $aTempTheme)
{
$aReturnValues[] = $aTempTheme["directory"];
}
return $aReturnValues;
}
final static public function getPathElements(string $anyNameOrPath = ""): array
{
return explode(
DIRECTORY_SEPARATOR,
str_replace(
LEPTON_PATH . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR,
"",
$anyNameOrPath
));
}
static public function createGUID(): string
{
if (function_exists('com_create_guid'))
{
$guid = com_create_guid();
$guid = strtolower($guid);
if (str_starts_with($guid, '{'))
{
$guid = substr($guid, 1);
}
if (strpos($guid, '}') == strlen($guid) - 1)
{
$guid = substr($guid, 0, strlen($guid) - 1);
}
return $guid;
}
else
{
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
random_int(0, 0xffff),
random_int(0, 0xffff),
random_int(0, 0xffff),
random_int(0, 0xffff),
random_int(0, 0x0fff) | 0x4000,
random_int(0, 0x3fff) | 0x8000,
random_int(0, 0xffff),
random_int(0, 0xffff)
);
}
}
}
static getInstance(array &$settings=[])
static copyThemeFilesRecursive(string $dirsource, string $dirdest, int $deep=0)
static rename_directories(array $directory_names=[])
static getAllThemes()
static getPathElements(string $anyNameOrPath="")
static setDisplay(bool $bUseDisplay=true)
static themeExists(string $sThemeName="")
static moveThemeFiles(string $sModuleDirectory="")
static createStandardProtection(string $path='/temp/secure/', string $username='')
static require_alternative(string $file_name, string $usage='backend')
static install_droplets(string $module_name='', string|array $zip_names=[])
static __callStatic(string $name, array $arguments)
static restoreStandardProtection()
static rename_table(string $table_name='')
static include_files(array|string $file_names=[], bool $interrupt=true)
static drop_table(string $table_name='')
static checkPasswordChars(string $sPassword)
static delete_obsolete_files(string|array ... $aFileNames)
static uninstall_droplets(string|array $droplet_names=[])
static restoreSpecialChars(string &$sAnyString, array $aAnyAssocArray=self::SPECIAL_CHARS_RESTORE)
static removeAllThemeFiles(string $sModuleDirectory="")
const ALT_FRONTEND_FILE
static upgrade_modules(string|array $module_names=[])
static install_table(string $table_name='', string $table_fields='')
static checkHexChars(string $sHexHash)
static create_sik_table(string $table_name='')
static install_modules(array $module_names=[])
static array_orderby(array $array, string $on, string $order=SORT_ASC)
static checkEmailChars(string $sEmail)
static delete_obsolete_directories(array $directory_names=[])
__call(string $name, array $arguments)
static checkUsernameChars(string $sName)
const SPECIAL_CHARS_RESTORE
static bool $display_errors
static getModuleDirectory(string $anyNameOrPath="")
static insert_values(string $table_name='', string $field_values='')
static decrypt_table(string $table_name='', array $aListOfFields=[], string $field_condition='')
static display(mixed $something_to_display="", string $tag="pre", string|null $css_class=null)
$database
Definition constants.php:52
load_module( $directory, $install=false)
rename_recursive_dirs(string $dirsource, string $dirdest, int $deep=0)
rm_full_dir(string $directory)