$GLOBALS["pnkit_mode"] = "online";$GLOBALS["pnkit_version"] = "2024-11-20T19:08:45+01:00";
/******************************************************************************/
// PORTABLE NKIT
//
// Usage online: eval (file_get_contents ("https://pnkit.fastsimple.com"));
// Usage offline: include "pnkit_main.php";
/******************************************************************************/
// START
// Less warnings PHP 8.1+
if (@!$_SERVER["REMOTE_ADDR"]) $_SERVER["REMOTE_ADDR"] = null;
if (@!$GLOBALS["pnkit_data_dir"]) $GLOBALS["pnkit_data_dir"] = null;
if (@!$GLOBALS["pnkit_public_cache_dir_internal"]) $GLOBALS["pnkit_public_cache_dir_internal"] = null;
if (@!$GLOBALS["pnkit_owner_ip"]) $GLOBALS["pnkit_owner_ip"] = null;
if (!function_exists("puuse")) { // Allow multiple loadings
$GLOBALS["MS_start"] = microtime(true);
register_shutdown_function (function(){register_shutdown_function (function(){ // Executing this code should be the last thing to do
$elapsed = microtime(true) - $GLOBALS["MS_start"];
file_put_contents ($GLOBALS['pnkit_data_dir'] . '/profile'.date ("H", time()).'.html', time()." ".$elapsed." ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."\n", FILE_APPEND);
if (!rand (0, 100)) @unlink ($GLOBALS['pnkit_data_dir'] . '/profile'.date ("H", time() - 6*3600).'.html');
});});
if (@exec('date +%Z')) date_default_timezone_set (timezone_name_from_abbr (exec('date +%Z'))); // Use the Linux OS timezone as PHP timezone
/******************************************************************************/
// MODULES
function file_get_contents_classic ($url)
{
$content = @file_get_contents ($url);
if (!$content) $content = @file_get_contents (str_replace ("https", "http", $url)); // E.g. Synology PHP does not do https
return $content;
}
function puuse()
{
global $PUUSE_Modules;
$modules = func_get_args();
if (!$modules || $modules==[""]) {
if ($PUUSE_Modules["all"] == 'loaded') return;
$PUUSE_Modules["all"] = 'loaded';
if ($GLOBALS['pnkit_mode'] == 'online') {
$all = unserialize(file_get_contents_classic("https://www.fastsimple.com/pnkit/pnkitweb_loader.php?allmodules=show"));
foreach ($all as $module => $php) {
if ($PUUSE_Modules[$module] != 'loaded') {
$PUUSE_Modules[$module] = 'loaded';
eval($php);
}
}
return;
} else {
$modules = puuse_allmodules();
}
}
foreach ($modules as $module) {
$module = strtolower($module);
if ($PUUSE_Modules[$module] != 'loaded') {
$PUUSE_Modules[$module] = 'loaded';
if ($GLOBALS['pnkit_mode'] == 'online') {
$php = file_get_contents_classic("https://fastsimple.com/pnkit/pnkitweb_loader.php?module=$module");
eval($php);
} else {
$pathinfo = pathinfo(__FILE__);
include $pathinfo['dirname'] . "/puuse_$module.php";
}
}
}
}
function puuse_allmodules()
{
if ($GLOBALS['pnkit_mode'] == 'online') {
$list = unserialize(file_get_contents_classic("https://www.fastsimple.com/pnkit/pnkitweb_loader.php?modulelist=show"));
return $list;
} else {
$pathinfo = pathinfo(__FILE__);
$d = dir($pathinfo["dirname"]);
while (false !== ($entry = $d->read())) {
if (strstr($entry, "puuse_")) {
$list[] = N_KeepAfter(N_KeepBefore($entry, ".php"), "puuse_");
}
}
$d->close();
return $list;
}
}
function muuse_register ($module, $relative_path)
{
if (!strlen (file_get_contents ($_SERVER['DOCUMENT_ROOT'].$relative_path))) die ("muuse_register: Fatal Error: Cannot find ".$_SERVER['DOCUMENT_ROOT'].$relative_path);
PMB_Save ("pnkit_modules", $module, $relative_path);
muuse_show ();
}
function muuse_remove ($module)
{
PMB_Delete ("pnkit_modules", $module);
muuse_show ();
}
function muuse_show ($as_title=false)
{
foreach (PMB_AllKeys ("pnkit_modules") as $module) {
if ($as_title) {
$content .= "[$module] ".PMB_Load ("pnkit_modules", $module)."\n";
} else {
$content .= "$module ".PMB_Load ("pnkit_modules", $module)."
";
}
}
$content .= 'Add modules with muuse_register ($module, $relative_path)'."\n".'Remove with muuse_remove ($module)';
if (!$as_title) echo $content; else return $content;
}
function muuse ()
{
global $MUUSE_Modules;
$modules = func_get_args();
if (!$modules || $modules==[""]) {
puuse(); // One call to load absolutely everything
$modules = PMB_AllKeys ("pnkit_modules");
}
foreach ($modules as $module) {
$module = strtolower($module);
if ($MUUSE_Modules[$module] != 'loaded') {
$MUUSE_Modules[$module] = 'loaded';
include $_SERVER['DOCUMENT_ROOT'].PMB_Load ("pnkit_modules", $module);
}
}
}
/******************************************************************************/
// BACKGROUND PROCESSING
function N_MultiExec ($code, $input=array())
{
$handle = N_GUID();
PMB_Save ("exec_now_code", $handle, $code);
PMB_Save ("exec_now_input", $handle, $input);
$GLOBALS["N_MultiExec"][$handle]["code"] = $code;
$GLOBALS["N_MultiExec"][$handle]["input"] = $input;
return $handle;
}
function N_MultiResult ($handle, $timeout = 5)
{
foreach ($GLOBALS["N_MultiExec"] as $h => $state) {
if (!$state["executed"]) {
$urls[] = ($_SERVER["REQUEST_SCHEME"] ? $_SERVER["REQUEST_SCHEME"] : "http") . "://" . $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?pnkitexecnow=$h";
$GLOBALS["N_MultiExec"][$h]["executed"] = true;
}
}
if ($urls) foreach (N_MultiGetPage ($urls, $timeout) as $url => $response) {
$h = N_KeepAfter ($url, "now=");
$result = unserialize ($response["content"]);
if ($result["status"]=="ok") {
$GLOBALS["N_MultiExec"][$h]["completed"] = true;
$GLOBALS["N_MultiExec"][$h]["output"] = $result["output"];
}
}
if (!$GLOBALS["N_MultiExec"][$handle]["completed"]) {
$input = $GLOBALS["N_MultiExec"][$handle]["input"];
eval ($GLOBALS["N_MultiExec"][$handle]["code"]);
$GLOBALS["N_MultiExec"][$handle]["completed"] = true;
$GLOBALS["N_MultiExec"][$handle]["output"] = $output;
}
return $GLOBALS["N_MultiExec"][$handle]["output"];
}
function N_MultiGetPage ($urls, $timeout = 5)
{
$multiHandle = curl_multi_init();
$curlHandles = [];
$headers = array();
$headers[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
// $headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
$headers[] = "Cache-Control: max-age=0";
$headers[] = "Connection: keep-alive";
$headers[] = "Keep-Alive: 300";
$headers[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$headers[] = "Accept-Language: en-us,en;q=0.5";
$headers[] = "Pragma: ";
foreach ($urls as $url) {
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, min (5, $timeout));
curl_setopt($handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
// curl_setopt($handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($handle, CURLOPT_AUTOREFERER, true);
curl_setopt($handle, CURLOPT_COOKIESESSION, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_multi_add_handle ($multiHandle, $handle);
$curlHandles[] = $handle;
}
$active = null;
do {
$mrc = curl_multi_exec ($multiHandle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM || $active);
$results = [];
foreach ($curlHandles as $handle) {
$url = curl_getinfo ($handle, CURLINFO_EFFECTIVE_URL);
$results[$url] = [
'content' => curl_multi_getcontent ($handle),
'response_code' => curl_getinfo ($handle, CURLINFO_HTTP_CODE),
];
curl_multi_remove_handle ($multiHandle, $handle);
curl_close ($handle);
}
curl_multi_close($multiHandle);
return $results;
}
function N_HandleExecNow ($exec_now_key)
{
$code = PMB_Load("exec_now_code", $exec_now_key);
$input = PMB_Load("exec_now_input", $exec_now_key);
eval ($code);
PMB_Flush();
echo serialize (array ("status"=>"ok", "output"=>$output));
PMB_Delete("exec_now_code", $exec_now_key);
PMB_Delete("exec_now_input", $exec_now_key);
}
function N_ExecInBackground ($code, $input = NULL)
{
global $exec_in_background_code, $exec_in_background_input;
if (!$exec_in_background_code) register_shutdown_function('N_FlushExecInBackground');
$exec_in_background_code[] = $code;
$exec_in_background_input[] = $input;
}
function N_FlushExecInBackground()
{
global $exec_in_background_code, $exec_in_background_input;
if ($exec_in_background_code) {
$key = N_GUID();
PMB_Save("exec_in_background_code", $key, $exec_in_background_code);
PMB_Save("exec_in_background_input", $key, $exec_in_background_input);
$url = ($_SERVER["REQUEST_SCHEME"] ? $_SERVER["REQUEST_SCHEME"] : "http") . "://" . $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"] . "?pnkitexec&key=$key";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100); // optimized value is 50, we use 100 to reduce chance of failure
curl_exec($ch);
$exec_in_background_code = $exec_in_background_input = array();
}
}
function N_HandleExecInBackground ($exec_in_background_key)
{
ignore_user_abort(true);
$exec_in_background_codes = PMB_Load("exec_in_background_code", $exec_in_background_key);
$exec_in_background_inputs = PMB_Load("exec_in_background_input", $exec_in_background_key);
if ($exec_in_background_codes) foreach ($exec_in_background_codes as $exec_in_background_index => $code) {
$input = $exec_in_background_inputs[$exec_in_background_index];
eval($code);
PMB_Flush();
}
PMB_Delete("exec_in_background_code", $exec_in_background_key);
PMB_Delete("exec_in_background_input", $exec_in_background_key);
}
function N_ExecInBackgroundBacklog()
{
$now = time();
$keys = PMB_Query("exec_in_background_code");
foreach ($keys as $key) {
N_HandleExecInBackground($key);
if (time() - $now > 300) break;
}
}
/******************************************************************************/
// ASSETS
function N_MimeMap()
{
return array('css' => 'text/css', 'js' => 'text/javascript', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'woff' => 'font/woff', 'woff2' => 'font/woff2', 'webp' => 'image/webp');
}
function N_ImageEmbedURL ($filename, $content)
{
$mimetype = N_MimeMap()[pathinfo($filename, PATHINFO_EXTENSION)];
return "data:$mimetype;base64,".base64_encode ($content);
}
function N_AssetContent ($subpath)
{
return N_Cache (24, "file_get_contents", "https://fastsimple.com/pnkit/$subpath");
}
function N_Asset($subpath = '')
{
if ($GLOBALS["N_AssetRelPath"]) {
return $GLOBALS["N_AssetRelPath"].$subpath;
}
if ($GLOBALS['pnkit_mode'] == 'online') {
$v = "v".PMB_Load ("pnkit", "last_pnkit_code_save");
$rp = $_SERVER['SCRIPT_NAME'] . "?v=$v&pnkitassets=/";
} else {
$pathinfo = pathinfo(str_replace('./', '/', N_getRelativePath($_SERVER['DOCUMENT_ROOT'], __FILE__)));
$rp = $pathinfo['dirname'] . '/';
}
return "$rp$subpath";
}
function N_DynAsset($mime, $asset_data)
{
if (strlen($asset_data) > 1024) {
$ext = array_search($mime, N_MimeMap());
if (!$ext) $ext = "txt";
$asset_id = md5($asset_data) . ".$ext";
if (!N_CacheAssetExists($asset_id)) N_CacheAssetSave($asset_id, $asset_data);
return N_CacheAsset($asset_id);
} else {
return $_SERVER['SCRIPT_NAME'] . '?pnkitdynasset&mime=' . urlencode($mime) . '&b64_data=' . urlencode(base64_encode($asset_data));
}
}
function N_CacheAsset($asset_id)
{
return $GLOBALS["pnkit_public_cache_dir_external"] . "/$asset_id";
}
function N_CacheAssetExists($asset_id)
{
return @file_exists($GLOBALS["pnkit_public_cache_dir_internal"] . "/$asset_id");
}
function N_CacheAssetSave($asset_id, $asset_data)
{
file_put_contents($GLOBALS["pnkit_public_cache_dir_internal"] . "/$asset_id", $asset_data);
}
function N_CacheAssetLoad($asset_id)
{
return file_get_contents($GLOBALS["pnkit_public_cache_dir_internal"] . "/$asset_id");
}
function N_CacheAssetDelete($asset_id)
{
@unlink($GLOBALS["pnkit_public_cache_dir_internal"] . "/$asset_id");
}
function N_PNFavIcon($minilabel = 'PN', $back="rgb(0,0,128)", $front = "white")
{
if ($minilabel=="|") {
return '';
} else if ($minilabel=="cube") {
return '';
}
puuse("ui");
$icon = '';
$icon .= '';
return $icon;
}
/******************************************************************************/
// PORTABLE NKIT DATABASE FUNCTIONS
function PMB_Merge ($table, $key, $merge)
{
$object = PMB_Load ($table, $key);
if (is_array ($object) && is_array ($merge)) {
foreach ($merge as $k => $v) {
$object[$k] = $v;
}
} else {
$object = $merge;
}
PMB_Save ($table, $key, $object);
}
function PMB_LoadTable ($table, $sort = '$key')
{
$result = array();
$keys = PMB_Query($table, '1==1', $sort);
foreach ($keys as $key => $dummy) {
$result[$key] = PMB_Load ($table, $key);
}
return $result;
}
function &PMB_Ref($table, $key)
{
if (!$table) trigger_error ("PMB_Ref($table, $key) needs a table ($table)", E_USER_ERROR);
if (!$key) trigger_error ("PMB_Ref($table, $key) needs a key ($key)", E_USER_ERROR);
global $PMB_FlushOnExit;
if (!$PMB_FlushOnExit) {
register_shutdown_function('PMB_FlushOnExit');
$PMB_FlushOnExit = true;
}
global $pmb_inmemorycache, $pmb_inmemorycopy;
if ($pmb_inmemorycache[$table][$key]) return $pmb_inmemorycache[$table][$key];
$pmb_inmemorycache[$table][$key] = PMB_Load($table, $key);
$pmb_inmemorycopy[$table][$key] = $pmb_inmemorycache[$table][$key];
return $pmb_inmemorycache[$table][$key];
}
function PMB_Flush()
{
global $pmb_inmemorycache, $pmb_inmemorycopy;
if (is_array($pmb_inmemorycache)) {
foreach ($pmb_inmemorycache as $table => $allrecords) {
foreach ($allrecords as $key => $object) {
if ($object != $pmb_inmemorycopy[$table][$key]) {
PMB_Save($table, $key, $object);
$pmb_inmemorycopy[$table][$key] = $object;
}
}
}
}
}
function PMB_FlushOnExit ()
{
PMB_Flush();
}
function PMB_FlushAndClean()
{
global $pmb_inmemorycache, $pmb_inmemorycopy;
PMB_Flush();
$pmb_inmemorycache = $pmb_inmemorycopy = array();
}
function PMB_Query($table, $constraint = '1==1', $sort = '$key')
{
if (!$constraint) $constraint = '1==1';
if (!$sort) $sort = '$key';
$GLOBALS["calls"]["PMB_Query"]++;
$GLOBALS["calllog"][] = "PMB_Query($table, $constraint, $sort)";
$result = array();
$keys = PMB_AllKeys($table);
foreach ($keys as $key) {
$record = PMB_Load($table, $key);
$match = false;
eval('$match = ' . $constraint . ';');
if ($match) {
eval('$result[$key] = ' . $sort . ';');
}
}
asort($result);
return $result;
}
function PMB_Save($table, $key, $object)
{
if (!$table) die("Fatal Error: PMB_Save needs a table ($key)");
if (!$key) die("Fatal Error: PMB_Save needs a key ($table)");
$GLOBALS["calls"]["PMB_Save"]++;
$GLOBALS["calllog"][] = "PMB_Save($table, $key, ...)";
$gz = function_exists("gzuncompress") && (substr($table, -3) == "_gz");
$ig = function_exists("igbinary_unserialize") && (substr($table, -3) == "_ig");
$key = N_Encode64(strtolower($key));
if (!file_exists($GLOBALS['pnkit_data_dir'] . "/$table")) {
mkdir($GLOBALS['pnkit_data_dir'] . "/$table");
}
$fd = fopen($GLOBALS['pnkit_data_dir'] . "/$table/{$key}_tmp", 'w');
if ($ig) {
fwrite($fd, igbinary_serialize($object));
} else {
if ($gz) {
fwrite($fd, gzcompress(serialize($object)));
} else {
fwrite($fd, serialize($object));
}
}
fclose($fd);
@rename($GLOBALS['pnkit_data_dir'] . "/$table/{$key}_tmp", $GLOBALS['pnkit_data_dir'] . "/$table/$key");
}
function PMB_TimeStamp($table, $key)
{
$GLOBALS["calls"]["PMB_TimeStamp"]++;
$GLOBALS["calllog"][] = "PMB_TimeStamp($table, $key)";
$key = N_Encode64(strtolower($key));
return filemtime($GLOBALS['pnkit_data_dir'] . "/$table/$key");
}
function PMB_Exists($table, $key)
{
$GLOBALS["calls"]["PMB_Exists"]++;
$GLOBALS["calllog"][] = "PMB_Exists($table, $key)";
$key = N_Encode64(strtolower($key));
return file_exists($GLOBALS['pnkit_data_dir'] . "/$table/$key");
}
function PMB_LastUpdate($table, $key)
{
$file = $GLOBALS['pnkit_data_dir'] . "/$table/" . N_Encode64(strtolower($key));
if (filesize($file)) {
return filemtime($file);
}
return false;
}
function PMB_Load($table, $key)
{
$GLOBALS["calls"]["PMB_Load"]++;
$GLOBALS["calllog"][] = "PMB_Load($table, $key)";
$gz = function_exists("gzuncompress") && (substr($table, -3) == "_gz");
$ig = function_exists("igbinary_unserialize") && (substr($table, -3) == "_ig");
global $PMB_Load;
$thekey = $key;
++$PMB_Load;
$key = N_Encode64(strtolower($key));
@$fd = fopen($GLOBALS['pnkit_data_dir'] . "/$table/$key", 'r');
if (!$fd) {
return null;
}
if (filesize($GLOBALS['pnkit_data_dir'] . "/$table/$key")) {
$rawdata = fread($fd, filesize($GLOBALS['pnkit_data_dir'] . "/$table/$key"));
fclose($fd);
if (strlen($rawdata)) {
if ($ig) {
$object = igbinary_unserialize($rawdata);
} else {
if ($gz) {
$object = unserialize(gzuncompress($rawdata));
} else {
$object = unserialize($rawdata);
}
}
}
return $object;
} else {
return null;
}
}
function PMB_DeleteTable($table, $please="")
{
if ($please!="please") throw new Error("PMB_DeleteTable requires 'please' as second parameter");
$keys = PMB_AllKeys ($table);
foreach ($keys as $key) {
PMB_Delete ($table, $key);
}
@rmdir($GLOBALS['pnkit_data_dir'] . "/$table");
}
function PMB_Delete($table, $key)
{
$GLOBALS["calls"]["PMB_Delete"]++;
$GLOBALS["calllog"][] = "PMB_Delete($table, $key)";
$key = N_Encode64(strtolower($key));
@unlink($GLOBALS['pnkit_data_dir'] . "/$table/$key");
}
function PMB_AllKeys($table)
{
$GLOBALS["calls"]["PMB_AllKeys"]++;
$GLOBALS["calllog"][] = "PMB_AllKeys($table)";
$dir = $GLOBALS['pnkit_data_dir'] . "/$table/";
$result = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (is_file($dir . $file) && !strstr ($file, "_tmp")) {
$result[] = N_Decode64($file);
}
}
closedir($dh);
}
}
sort($result);
return $result;
}
function PMB_TableBytes($table)
{
$GLOBALS["calls"]["PMB_TableBytes"]++;
$GLOBALS["calllog"][] = "PMB_TableBytes($table)";
$dir = $GLOBALS['pnkit_data_dir'] . "/$table/";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (is_file($dir . $file)) {
$result += filesize($dir . $file);
}
}
closedir($dh);
}
}
return $result;
}
function PMB_AllTables()
{
$GLOBALS["calls"]["PMB_AllTables"]++;
$GLOBALS["calllog"][] = "PMB_AllTables()";
$dir = $GLOBALS['pnkit_data_dir'] . "/";
$result = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($subdir = readdir($dh)) !== false) {
if (is_dir($dir . $subdir) && $subdir != "." && $subdir != ".." && substr($subdir, 0, 4) != "int_") {
$result[] = $subdir;
}
}
closedir($dh);
}
}
sort($result);
return $result;
}
function PMB_Check($type = "all")
{
if ($type == "all" || $type == "gz") {
$tables = PMB_AllTables();
foreach ($tables as $table) {
if (substr($table, -3) == "_gz") {
$keys = PMB_AllKeys($table);
$ctr = 0;
echo "
$table: " . N_Count ($keys) . "
";
echo str_pad('', 4096);
flush();
foreach ($keys as $key) {
$file = N_Encode64(strtolower($key));
@$fd = fopen($GLOBALS['pnkit_data_dir'] . "/$table/$file", 'r');
if (!$fd) {
echo "ERROR: No file for key: $key ($file)
";
} else {
if (!filesize($GLOBALS['pnkit_data_dir'] . "/$table/$file")) {
echo "ERROR: No data (empty file) for key: $key ($file)
";
} else {
$rawdata = fread($fd, filesize($GLOBALS['pnkit_data_dir'] . "/$table/$file"));
fclose($fd);
if (!N_ValidGZ($rawdata)) {
echo "ERROR: No valid data (gzuncompress data error) for key: $key ($file)
";
}
}
}
++$ctr;
if ($ctr % 1000 == 0) {
echo "Progress $ctr/" . N_Count ($keys) . "
";
echo str_pad('', 4096);
flush();
}
}
echo "Progress $ctr/" . N_Count ($keys) . "
";
}
}
}
if ($type == "all" || $type == "ig") {
$tables = PMB_AllTables();
foreach ($tables as $table) {
if (substr($table, -3) == "_ig") {
$keys = PMB_AllKeys($table);
$ctr = 0;
echo "
$table: " . N_Count ($keys) . "
";
echo str_pad('', 4096);
flush();
foreach ($keys as $key) {
$file = N_Encode64(strtolower($key));
@$fd = fopen($GLOBALS['pnkit_data_dir'] . "/$table/$file", 'r');
if (!$fd) {
echo "ERROR: No file for key: $key ($file)
";
} else {
if (!filesize($GLOBALS['pnkit_data_dir'] . "/$table/$file")) {
echo "ERROR: No data (empty file) for key: $key ($file)
";
} else {
$rawdata = fread($fd, filesize($GLOBALS['pnkit_data_dir'] . "/$table/$file"));
fclose($fd);
if (!igbinary_unserialize($rawdata)) {
echo "WARNING: No data for key: $key ($file)
";
}
}
}
++$ctr;
if ($ctr % 1000 == 0) {
echo "Progress $ctr/" . N_Count ($keys) . "
";
echo str_pad('', 4096);
flush();
}
}
echo "Progress $ctr/" . N_Count ($keys) . "
";
}
}
}
if ($type == "all" || $type == "std") {
$tables = PMB_AllTables();
foreach ($tables as $table) {
if (substr($table, -3) != "_ig" && substr($table, -3) != "_gz") {
$keys = PMB_AllKeys($table);
$ctr = 0;
echo "
$table: " . N_Count ($keys) . "
";
echo str_pad('', 4096);
flush();
foreach ($keys as $key) {
$file = N_Encode64(strtolower($key));
@$fd = fopen($GLOBALS['pnkit_data_dir'] . "/$table/$file", 'r');
if (!$fd) {
echo "ERROR: No file for key: $key ($file)
";
} else {
if (!filesize($GLOBALS['pnkit_data_dir'] . "/$table/$file")) {
echo "ERROR: No data (empty file) for key: $key ($file)
";
} else {
$rawdata = fread($fd, filesize($GLOBALS['pnkit_data_dir'] . "/$table/$file"));
fclose($fd);
if (!unserialize($rawdata)) {
echo "WARNING: No data for key: $key ($file)
";
}
}
}
++$ctr;
if ($ctr % 1000 == 0) {
echo "Progress $ctr/" . N_Count ($keys) . "
";
echo str_pad('', 4096);
flush();
}
}
echo "Progress $ctr/" . N_Count ($keys) . "
";
}
}
}
}
/******************************************************************************/
// PHP 5.4 support
if (!function_exists("array_key_last")){
function array_key_last ($array) {
$array = NA ($array);
end ($array);
return key ($array);
}
}
/******************************************************************************/
// 1001 USEFUL SMALL FUNCTIONS
function N_AccurateTime ()
{
foreach (["time.cloudflare.com", "pool.ntp.org", "time.google.com", "time.apple.com"] as $timehost) {
if ($socket = @fsockopen("udp://$timehost", 123, $errno, $errstr, 1)) {
stream_set_timeout ($socket, 1);
fwrite ($socket, "\010" . str_repeat("\0", 47));
$response = fread ($socket, 48);
fclose($socket);
if ($response && strlen($response) === 48) {
$data = unpack('N12', $response);
$timestamp = sprintf('%u', $data[9]);
$timestamp -= 2208988800; // Convert NTP time to Unix timestamp (1900-01-01)
if ($timestamp > 1730000000) return $timestamp;
}
}
}
$response = @json_decode (@file_get_contents ("https://timeapi.io/api/time/current/zone?timeZone=Europe/Amsterdam"), true);
if ($response && isset($response['dateTime'])) {
$dateTime = new DateTime($response['dateTime'], new DateTimeZone('Europe/Amsterdam'));
$timestamp = $dateTime->getTimestamp();
if ($timestamp > 1730000000) return $timestamp;
}
return time();
}
function N_SemaClaim ($sema, $wait=15, $seconds=7200)
{
for ($i=0; $i<=$wait*10; $i++) {
if (PMB_Load ("semaphores", $sema) + $seconds < time()) {
PMB_Save ("semaphores", $sema, time());
return true;
}
usleep (100000);
}
return false;
}
function N_SemaRelease ($sema)
{
PMB_Save ("semaphores", $sema, 0);
}
function N_SemaPulse ($sema)
{
PMB_Save ("semaphores", $sema, time());
}
function N_ReplaceDiacritics ($string) {
$originalCharacters = array(
'ä', 'ë', 'ï', 'ö', 'ü', 'á', 'é', 'í', 'ó', 'ú', 'ý', 'à', 'è', 'ì', 'ò', 'ù', 'â', 'ê', 'î', 'ô', 'û', 'ã', 'ñ', 'õ', 'å', 'æ', 'ç', 'œ',
'Ä', 'Ë', 'Ï', 'Ö', 'Ü', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ý', 'À', 'È', 'Ì', 'Ò', 'Ù', 'Â', 'Ê', 'Î', 'Ô', 'Û', 'Ã', 'Ñ', 'Õ', 'Å', 'Æ', 'Ç', 'Œ'
);
$replacementCharacters = array(
'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'y', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'n', 'o', 'a', 'ae', 'c', 'oe',
'A', 'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'Y', 'A', 'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'A', 'N', 'O', 'A', 'AE', 'C', 'OE'
);
return str_replace($originalCharacters, $replacementCharacters, $string);
}
function N_SecureMultiRand ($amount, $min, $max, $type="test")
{
$microtime = microtime(true);
$slot = (int)($microtime/(24*3600));
$seed_index = 1 + NN (PMB_Load ("multi_rand", "seed_index"));
PMB_Save ("multi_rand", "seed_index", $seed_index);
$mt_seed = ((int)$microtime * $amount * $seed_index) % 2147483647;
mt_srand ($mt_seed, MT_RAND_MT19937);
for ($i = 0; $i < $amount; $i++) $result[$i] = mt_rand($min, $max);
$result ["type"] = $type;
$result ["min"] = $min;
$result ["max"] = $max;
$result ["seed_index"] = $seed_index;
$result ["microtime"] = $microtime;
$result ["mt_seed"] = $mt_seed;
$log = PMB_Load ("multi_rand", $slot);
$log[] = $result;
PMB_Save ("multi_rand", $slot, $log);
return $result;
}
function N_ContainsAny ($haystack, $needle) { // https://www.fastsimple.com/pnkit/example_online.php?pnkit=eval&saved_code=684c346e5f98dfbad845ef9a8b5ffdaa
if (is_array ($haystack)) {
foreach ($haystack as $h) if (N_ContainsAny ($h, $needle)) return true;
return false;
} if (is_array ($needle)) {
foreach ($needle as $n) if (false !== stripos($haystack, $n)) return true;
return false;
} else {
return false !== stripos($haystack,$needle);
}
}
function N_ArrayToTable ($array, $table_spacing ='cellpadding="5" cellspacing="0"', $table_cell_properties='style="border: 1px solid; border-color:#eee;"') {
if (!is_array($array)) return N_ArrayToTable ([NS($array)=>""]);
$table = "
".htmlentities ($key)." | ";
if (is_array($value)) {
$table .= N_ArrayToTable ($value, $table_spacing, $table_cell_properties);
} else {
$table .= "".str_replace ([" ", "\n"], [" ", " "], htmlentities ($value)).""; } $table .= " |
";
if (N_CLI()) {
if (is_array($object)) {
echo '(arr: ' . N_Count ($object) . ')'.PHP_EOL;
print_r($object);
} else if (is_string($object)) {
echo '(str: ' . strlen($object) . ') '.PHP_EOL;
print_r($object);
} else if (is_boolean($object)) {
echo '(' . gettype($object) . ') '.PHP_EOL;
echo $object ? "true" : "false";
} else {
echo '(' . gettype($object) . ') '.PHP_EOL;
print_r($object);
}
} else {
echo ''; if (is_array($object)) { echo '(arr: ' . N_Count ($object) . ')'.PHP_EOL; echo htmlentities(print_r($object, 1), 2, 'ISO-8859-1'); // ENT_COMPAT | ENT_HTML401 = 2 } else if (is_string($object)) { echo '(str: ' . strlen($object) . ') '.PHP_EOL; echo htmlentities(print_r($object, 1), 2, 'ISO-8859-1'); // ENT_COMPAT | ENT_HTML401 = 2 } else if (is_bool($object)) { echo '(' . gettype($object) . ') '.PHP_EOL; echo $object ? "true" : "false"; } else { echo '(' . gettype($object) . ') '.PHP_EOL; echo htmlentities(print_r($object, 1), 2, 'ISO-8859-1'); // ENT_COMPAT | ENT_HTML401 = 2 } echo ''; // ENT_COMPAT | ENT_HTML401 = 2 } if (count ($args) > 1) echo " | ";
}
if (count ($args) > 1) echo "
' : ''; $offset = 0; $len = strlen($data); $x = ($uppercase === false) ? 'x' : 'X'; for ($i = $j = 0; $i < $len; ++$i) { $hexi .= sprintf("%02$x ", ord($data[$i])); if (ord($data[$i]) >= 32) { $ascii .= ($htmloutput === true) ? htmlentities($data[$i]) : $data[$i]; } else { $ascii .= '.'; } if ($j === 7 || $j === 13 || $j === 23) { $hexi .= ' '; $ascii .= ' '; } if (++$j === 32 || $i === $len - 1) { $dump .= sprintf("%04$x %-49s %s", $offset, $hexi, $ascii); $hexi = $ascii = ''; $offset += 32; $j = 0; if ($i !== $len - 1) { $dump .= "\n"; } } } $dump .= $htmloutput === true ? '' : ''; $dump .= "\n"; return $dump; } function N_GUID($chars = 32) { if ($chars > 32) { return N_GUID() . N_GUID($chars - 32); } else { global $LastGUID; $LastGUID = md5(getmypid() . time() . microtime() . serialize($_SERVER) . $LastGUID); return substr($LastGUID, 0, $chars); } } function N_Year() { return date('Y'); } function N_Regexp($string, $patern, $index = 1) { if (preg_match_all("#$patern#i", $string, $matches) === false) { return null; } return $matches[0][$index - 1]; } function N_Windows() { return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; } function N_GetPage ($url, $maxms=-1) { if ($maxms != -1) { $ch = curl_init($url); curl_setopt ($ch, CURLOPT_TIMEOUT_MS, 1000 + $maxms); // maximum time the transfer is allowed to complete curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT_MS, 100 + $maxms); // timeout for the connect phase curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); return curl_exec($ch); } else { return file_get_contents($url); } } function N_KeepAfter($body, $marker) { if ('' . $marker == '') { return $body; } if (strpos($body, $marker) === false) { return ''; } else { return substr($body, strpos($body, $marker) + strlen($marker)); } } function N_KeepBefore($body, $marker) { if ('' . $marker == '') { return $body; } if (strpos($body, $marker) === false) { return ''; } else { return substr($body, 0, strpos($body, $marker)); } } } // if (!function_exists("N_SortBy")) if (!function_exists('array_key_first')) { // PHP 7.3 function array_key_first(array $arr) { foreach ($arr as $key => $unused) { return $key; } return NULL; } } /******************************************************************************/ // INTERACTIVE FACILITIES function N_PNKIT() { if ($GLOBALS["pnkit_mode"] != "online") $GLOBALS["pnkit_mode"] = "offline"; if ($_SERVER["REMOTE_ADDR"] != $GLOBALS["pnkit_owner_ip"] && $_SERVER["REMOTE_ADDR"] != "127.0.0.1") die(); if ($_REQUEST["pnkit"] == "evalnow") { echo "🗎
";
foreach ($dirs as $e) {
$extra = "";
if (!strstr($e, "pnkit_")) if ($search) if (!in_array ($e, $skiplist)) {
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("$dir/$e"));
$rii->setMaxDepth(0);
foreach ($rii as $x) {
if (is_file($x->getPathname()) && filesize($x->getPathname()) < 1024 * 1024) {
if (in_array (strtolower (pathinfo ($x->getPathname(), PATHINFO_EXTENSION)), $validextensions)) {
$content = file_get_contents($x->getPathname());
if (stripos(" $content", $search)) $extra = "FOUND";
}
}
}
} else {
$extra = "skipped";
}
if ($search) {
echo "[$e] $extra \n"; } else { echo "[$e] $extra \n"; } } echo " "; foreach ($files as $e) if (strpos($e, ".php")) { // All php files $extra = ""; if ($search) { $content = file_get_contents("$dir/$e"); if (stripos(" $content", $search)) $extra = "FOUND"; } echo "[$e] $extra \n"; } echo " "; foreach ($files as $e) if (!strpos($e, ".php")) { // All other files < 1 MB $extra = ""; if ($search && filesize("$dir/$e") < 1024 * 1024 && in_array (strtolower (pathinfo ($e, PATHINFO_EXTENSION)), $validextensions)) { $content = file_get_contents("$dir/$e"); if (stripos(" $content", $search)) $extra = "FOUND"; } echo "[$e] $extra \n"; } echo " | ";
$sortedfiles_subs = array();
foreach ($dirs as $e) {
if (!strstr($e, "pnkit_")) if (!in_array ($e, $skiplist)) {
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("$dir/$e"));
$rii->setMaxDepth(0);
foreach ($rii as $x) {
if (is_file($x->getPathname()) && filesize($x->getPathname()) < 1024 * 1024) {
if (in_array (strtolower (pathinfo ($x->getPathname(), PATHINFO_EXTENSION)), $validextensions)) {
$sortedfiles_subs[filemtime ($x->getPathname())] = str_replace ("$dir/", "", $x->getPathname());
}
}
}
}
}
$ctr = 0;
foreach ($sortedfiles as $t => $e) if (strpos($e, ".php") || strpos($e, ".css") || strpos($e, ".scss") || strpos($e, ".js")) {
echo "".date ("Y-m-d H:i:s", $t)." [$e] \n"; if (++$ctr==10) break; } echo " "; krsort($sortedfiles_subs); $ctr = 0; foreach ($sortedfiles_subs as $t => $e) if (strpos($e, ".php") || strpos($e, ".css") || strpos($e, ".scss") || strpos($e, ".js")) { echo "".date ("Y-m-d H:i:s", $t)." [$e] \n"; if (++$ctr==10) break; } echo " |