From 53b5ebcb433334b9dbd50a921178b881f177d691 Mon Sep 17 00:00:00 2001 From: Matthieu Bessat Date: Sun, 3 Oct 2021 10:39:21 +0200 Subject: [PATCH] feat(BaseConverter): create module --- config.example.php | 5 +- modules/baseconverter/baseconverter.php | 95 ++++++++++++++++++++ modules/baseconverter/baseconverter_help.php | 20 +++++ 3 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 modules/baseconverter/baseconverter.php create mode 100644 modules/baseconverter/baseconverter_help.php diff --git a/config.example.php b/config.example.php index 9570c69..a683c28 100644 --- a/config.example.php +++ b/config.example.php @@ -20,7 +20,10 @@ return [ 'logator' => [ 'alias' => ['logme'] ], - 'hash' => [] + 'hash' => [], + 'baseconverter' => [ + 'alias' => ['encode', 'decode'] + ] ], 'auth' => [ 'root' => 'password' diff --git a/modules/baseconverter/baseconverter.php b/modules/baseconverter/baseconverter.php new file mode 100644 index 0000000..a5eb421 --- /dev/null +++ b/modules/baseconverter/baseconverter.php @@ -0,0 +1,95 @@ + 36) { + echo "ERR: Can't convert from base strictly superior to 36"; + http_response_code(400); + exit(); + } + $inter = base_convert($input, $fromBase, 10); +} + +$output = $inter; +switch ($to) { + case 'base64': + $output = base64_encode($inter); + break; + case 'dec': + $value = unpack('H*', $inter); + $output = base_convert($value[1], 16, 10); + break; + case 'bin': + if (is_numeric($inter)) { + $output = decbin($inter); + } else { + $value = unpack('H*', $inter); + $output = base_convert($value[1], 16, 2); + } + break; + case 'hex': + if (is_numeric($inter)) { + $output = dechex($inter); + } else { + $output = unpack('H*', $inter)[1]; + } + break; + case 'octal': + if (is_numeric($inter)) { + $output = decoct($inter); + } else { + $value = unpack('H*', $inter); + $output = base_convert($value[1], 16, 8); + } + break; +} + +if (preg_match('/^base[0-9]+$/m', $to) && $output === $inter) { + $toBase = (int) str_replace('base', '', $to); + if ($toBase > 36) { + echo "ERR: Can't convert to base strictly superior to 36"; + http_response_code(400); + exit(); + } + $output = base_convert($input, 10, $toBase); +} + +echo $output; diff --git a/modules/baseconverter/baseconverter_help.php b/modules/baseconverter/baseconverter_help.php new file mode 100644 index 0000000..dc0bfde --- /dev/null +++ b/modules/baseconverter/baseconverter_help.php @@ -0,0 +1,20 @@ + 'Base Converter', + 'description' => 'Convert from base to base easily', + 'actions' => [ + [ + 'name' => 'Convert from base64 to string', + 'path' => '/?from=base64&data=dGhhdCdzIGNvb2wgaHVoPwo=' + ], + [ + 'name' => 'Convert decimal to hex', + 'path' => '/?from=hex&data=2a' + ], + [ + 'name' => 'Convert string to decimal', + 'path' => '/?to=dec&data=hello' + ] + ] +];