Decodener

PHP source file
<?php
const VERSION = "1.2.1";
$CODE = (empty($_POST['option'])) ? '' : $_POST['option'];
?>
<!DOCTYPE html>
<html>
<head>
<title><?=$CODE?> DEcodENer v<?=VERSION?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Andova Begarin">
<meta name="copyright" content="public domain">
<style>
body{font-family:'Courier New';font-size:15px} pre{font-size:14px}section{margin-bottom:10px} form{margin-bottom:10px}
textarea{width:540px;height:240px;padding:1px 0px 1px 2px;float:left;overflow-y:scroll}button{width:76px;margin:2px 4px 
0 0;font-family:inherit;font-size:inherit}input[type=text]{width:186px;margin:0px 2px 1px 0px; padding:1px 0px 1px 3px; 
font-family:inherit; font-size:inherit}input[type="radio"]{margin:3px 4px 3px 4px;vertical-align:-2px}
input[type="checkbox"]{margin:3px 4px 3px 6px;vertical-align:-3px}input#a{margin-left:207px}.indent{margin:3px 0px 2px 12px}
</style>
</head>
<body id="">

<?php
set_error_handler("errorhand");
ini_set('error_append_string',"<br>");

// The programs you have. The first few are expected to be in PATH. The 
// others are different. See the PHP example for how, if you want, to 
// add a path. Cygwin is recommened as it comes with many languages.
define('PERL','perl');
define('BASH','bash');
define('RUBY','ruby');
define('PYTHON','python');
define('PHP','php.exe');
//define('PHP','c:/bin/php/php.exe');	// or put in where it is

// Golang is really odd and not like all other languages (which can 
// just run).
define('GOPATH',getenv('GOPATH'));
define('GOROOT',getenv('GOROOT'));
if (strstr($_SERVER['PATH'],'go.exe'))		// go in path
	define('GOEXEC','go.exe');
elseif (strstr($_SERVER['PHP_SELF'],'/'))	// Cygwin
	define('GOEXEC',str_replace('\\','/',GOROOT).'/bin/go.exe');
else
	define('GOEXEC',GOROOT.'\\bin\\go.exe');// Windows

// Perl 6 (rakudo) is in it's own place...
if (strstr($_SERVER['PATH'],'perl6'))		// in path
	define('RAKUDO','perl6');
elseif (strstr($_SERVER['PHP_SELF'],'/'))	// Cygwin
	define('RAKUDO','/cygdrive/c/rakudo/bin/perl6.bat');
else
	define('RAKUDO','\\rakudo\\bin\\perl6.bat');// Windows

// default the main option; define the others
$option = "php";
$post = $data = $button = $func = $print = $farg = $search = $replace = "";
$text = $run = $import = $below = $args = $html = $exec = $aget = $dump = "";
$save = $fname = '';
// all form inputs must be defined so that there are no undefined errors 
// when this code is first run; and the need to not stomp on any possible 
// variables one may want to use here (like $res, $replac, $searc, ... below)
extract($_POST);
$data = str_replace("\r","",$data);
$error = $res = $message = '';

function DATA_PROCESS(){} // for editor that provides function lists (bookmarks)

# NOTEF

// if GET checked make $_GET
if ($aget) {
	foreach (explode(",",$args) as $u)
		$_GET[$u] = "";
}

// if import load a tmp file (to fill the textarea) and redisplay the form
if ($import) {
	// name is already validated
	$data = file_get_contents($import);
	if (strrpos($import,".rul")) $option = "rulz";
	if (strrpos($import,".pl")) $option = "perl";
	if (strrpos($import,".sh")) $option = "bash";
	if (strrpos($import,".php")) {
		$option = "php";
		$data = preg_replace("/^<\?php\n/",'',$data);
	}
	if (strrpos($import,".p6")) {
		$option = "perl6";
		$data = str_replace("use v6;\n",'',$data);
	}
	if (strrpos($import,".go")) {
		$option = "go";
		// kinda goofy to remove first few lines and then last two lines
		// but maybe put back an explicit import line
		$data = explode("\n",$data);
		$im = $data[1]; // import line
		unset($data[0]); unset($data[1]); unset($data[2]);
		if (strpos($im,'/') !== false)
			array_unshift($data,$im);
		unset($data[count($data)-1]);
		$data = implode("\n",$data); // the trailing "}"
	}
} else
// we have EXEC input data
if ($exec) {
	$res = code_exec($data,$button,$exec);
} else
// we have data and the data is going to be processed/executed
# NOTED
if ($data) {
// run/search first
	if ($run && $search) {
		$replac = un_escape($replace);		// note: 2 variables!
		if ($search[0] == '/' && preg_match('/\/[a-zA-Z]*$/',$search))
			$res = preg_replace($search,$replac,$data);
		else {
			$searc = un_escape($search);	// note: 2 variables!
			$res = str_replace($searc,$replac,$data);
		}
	}
// run function
	elseif ($run && $func) {
		if (function_exists($func)) {
			if (!$print) {
				// function prints data; capture it
				ob_start();
			}
			// runc the function; store return
			if ($farg) {
				$s = $func($data,$farg);
			} else {
				$s = $func($data);
			}
			if (!$print) {
				// get output
				$res = ob_get_contents();
				ob_end_clean();
			} else {
				// it's the return, stupid
				$res = $s;
			}
		} else {
			// set result to error message
			$res = "function $func not defined";
		}
// code_$option function - the main radio buttons
	} else {
		if (function_exists($f='code_'.$option)) {
			$res = $f($data,$button,$args);
		} else {
			$res = "function code_$option not defined";
		}
	}
}

if ($text) {			// apply to textarea
	$data = $res;
}
if (!$text && $below == "") {	// print here or below...
	print_out($res,$html);
}
if ($error) {			// if error just say it
	echo "PHP $error<br>\n";
	$error = "";
}

$args = htmlentities($args);	// sanitize these (for form)
$data = htmlentities($data);
$search = htmlentities($search);
$replace = htmlentities($replace);

function DATA_FORM(){}
?>
<div style='float:left'><b>DEcodENer v<?=VERSION?></b></div>
<form method="post" action="?">
<input id="a" type="text" name="args" title="data to pass to program" value="<?=$args?>" />arguments
<span><input title="pass as $_GET (comma delimited)" type="checkbox" <?=c($aget)?> name="aget">GET</span><br>
<textarea name="data"><?=$data?></textarea>
<div>
<?php
function DATA_INPUTS(){} 
/* this is BAD code... */
?>
<!-- data type choices html - see matching code_<value>() functions -->
<span title="PHP code"><input type="radio" name="option" <?=c($option,'php')?> value="php">PHP</span>
<span title="Go code"><input type="radio" name="option" <?=c($option,'go')?> value="go">Go</span>
<span title="shell code"><input type="radio" name="option" <?=c($option,'bash')?> value="bash">Bash</span>
<span title="Perl code"><input type="radio" name="option" <?=c($option,'perl')?> value="perl">Perl</span><br/>
<span title="Perl6 code"><input type="radio" name="option" <?=c($option,'perl6')?> value="perl6">Perl6</span>
<span title="Python"><input type="radio" name="option" <?=c($option,'py')?> value="py">Python</span>
<span title="Ruby code"><input type="radio" name="option" <?=c($option,'ruby')?> value="ruby">Ruby</span>
<span title="Win CMD"><input type="radio" name="option" <?=c($option,'CMD')?> value="CMD">CMD</span><br/>
<span title="url coded"><input type="radio" name="option" <?=c($option,'url')?> value="url">URL</span><br/>
<span title="base64 coded"><input type="radio" name="option" <?=c($option,'64')?> value="64">base64</span> 
<span title="base64 data"><input type="radio" name="option" <?=c($option,'img64')?> value="img64">base64 img</span><br/>
<span title='HTML'><input type='radio' name='option' <?=c($option,'html')?> value='html'>HTML</span><br/>
<span title='JSON coded'><input type='radio' name='option' <?=c($option,'json')?> value='json'>JSON</span><br/>
<span title='Gmail URL coded'><input type='radio' name='option' <?=c($option,'gurl')?> value='gurl'>GUrl</span><br/>
<span title='HEX format'><input type='radio' name='option' <?=c($option,'hex')?> value='hex'>HEX</span><br/>
<span title='sekret css content'><input type='radio' name='option' <?=c($option,'sekret')?> value='sekret'>sekret</span><br/>
<!-- adding is:
     1) an input like above
     2) function named "code_$option"
     (this needs to be built via a "make" file - see NOTEM)
-->
<span style="margin-left:4px" title="exec program on data (has precedence)">exec:<input type="text" name="exec" value="<?=$exec?>" style="width: 300px;"/></span><br/>
<button style="margin:4px" title="save textarea to file" name="button" value="save">save</button>
<input type="text" name="fname" value="<?=$fname?>" style="width:256px;"/>
</div>
<br/>
<br clear="all" />
<?php
function CONTROL_BUTTONS(){} ?>
<div>
<!-- decode/encode (either) are also for exec'ing code or import of tmp file -->
<button title="encode/exec data" name="button" value="decode">decode</button><button title="decode/exec data" name="button" value="encode">encode</button><span title="import temp file">import: <?=tmp()?></span>
</div>
<!-- no newlines is to line entities up right in browser - see decodener.txt -->
<div class="indent"><span title="result into textarea"><input type="checkbox" <?=c($text)?> name="text">text</span> <button title="run function or search & replace" name="run" value="run">run</button><input title="PHP function for data" type="text" name="func" value="<?=$func?>"><span title="2nd arg (optional)"><input type="text" name="farg" value="<?=$farg?>"></span><span title="PHP function for data">function</span><span title="print function return"><input type="checkbox" <?=c($print)?> name="print">print</span>
<br>
<span title="output below form"><input type="checkbox" <?=c($below)?> name="below" />below</span><input style="margin-left:80px" title="search (if within // it's a regex)" type="text" name="search" value="<?=$search?>"><input title="can use \n, \r, \t; \\n, \\r, \\t" type="text" name="replace" value="<?=$replace?>"><span>search &amp; replace</span>

<!-- other text inputs can/may go here -->

<!-- output options -->
<br>
<span title="output is HTML"><input type="checkbox" <?=c($html)?> name="html">html</span>
<br>
<span title="dump some data"><input type="checkbox" <?=c($dump)?> name="dump">debug</span>

</div> <!-- end indent div -->

<!-- final thing -->
<div style="margin:3px 0px 2px 16px"><a href="<?=$_SERVER['PHP_SELF']?>">reset</a></div>

</form> <!-- end FORM -->
<?=$message?>

<?php
function END_FORM(){}

// output below HTML
if (!$text && $below == "on") {
	print_out($res,$html);
}

// debugging output
if ($dump) {
	echo "<pre>--\n\n";
	echo '$_GET: ',print_r($_GET,true),'$_POST: ',print_r($_POST,true);
	$defs = get_defined_constants(true);
	echo 'CONSTANTS: ',print_r($defs['user'],true);
	echo '$GLOBALS: ';
	foreach (array('_GET','_POST','_COOKIE','_FILES','_SERVER','defs') as $u)
		unset($GLOBALS[$u]);
	unset($u);
	print_r($GLOBALS['GLOBALS']);
}

## RUN CODE
/*
   usage:
		if (function_exists($f='code_'.$option)) {
			$res = $f($data,$button,$args);
   The functions get $data, $dir and $args; dir is either "encode" or "decode", 
   which are the buttons.

   For the code functions $dir is ignored (so either will button work). The 
   "run" button will also work.

   There is one "pre function" for each language, and one code exec function 
   for all. A temporary file is used name "tmp" with extension indicative of 
   the language.
*/

function code_html($data, $dir, $args) {
$GLOBALS['html'] = 1;
	return "<div class='dec' id='dec'>$data</div>";
}

function code_php($data, $dir, $args) {
/*
   The PHP code can't start "mixed" unless a "?>" pair used like:

   ?>
   foo
   <?php
   print $argv[1];
*/
	$data = "<?php\n" . $data;
	$d = file_put_contents("tmp.php",$data);
if (0) {
	var_dump($d);
	exit();
}
	$cmd = PHP . " tmp.php $args";
	return codeexec($cmd);
}

function code_go($data, $dir, $args) {
/*
   Go needs an import block; there are two ways to do so:

   1) manually added imports via first line:

      import("crypto/rand";"math/big";"fmt";)
      b := new(big.Int).SetInt64(int64(6))
      i, _ := rand.Int(rand.Reader, b)
      fmt.Printf("%#v\n",i)

   2) look for imports based on "[a-z]{2,}\.":

      p := regexp.MustCompile("foo")
      s := p.FindString("foobar")
      fmt.Printf("%#v\n",s)

      Probably not foolproof, but this is only for small pieces of code.

   An explicit import line is only needed for "path/pkg" packages.

   Does not allow for func definitions - use closures.
*/
	$im = "";
	if (preg_match('/^import\s*\((.*)\)/',$data,$m)) {
		$data = preg_replace('/^import\s*\((.*)\)/','',$data);
		foreach (explode(",",$m[1]) as $i) {
			$i = trim($i);
			$im .= $i;
		}
	} else {
		preg_match_all('/(?:\s|^)([a-z]{2,})\.[A-Z]/',$data,$m);
		foreach ($m[1] as $i) {
			if (!strstr($im,$i)) { // only add once
				$im .= "\"$i\";";
			}
		}
	}
	$data = trim($data);
$go = <<<GC
package main
import ($im)
func main() {
$data
}
GC;
	file_put_contents("tmp.go",$go);
	$cmd = GOEXEC . " run tmp.go $args";
	return codeexec($cmd);
}

function code_perl($data, $dir, $args) {
	file_put_contents("tmp.pl",$data);
	$cmd = PERL . " tmp.pl $args";
	return codeexec($cmd);
}

function code_perl6($data, $dir, $args) {
	$data = "use v6;\n" . $data;
	file_put_contents('tmp.p6',$data);
	$cmd = RAKUDO . ' tmp.p6 ' . $args;
	return codeexec($cmd);
}

function code_bash($data, $dir, $args) {
	file_put_contents("tmp.sh",$data);
	$cmd = BASH . " tmp.sh $args";
	return codeexec($cmd);
}

function code_ruby($data, $dir, $args) {
	file_put_contents("tmp.rb",$data);
	$cmd = RUBY . " tmp.rb $args";
	return codeexec($cmd);
}

function code_py($data, $dir, $args) {
	file_put_contents("tmp.py",$data);
	$cmd = PYTHON . " tmp.py $args";
	return codeexec($cmd);
}

## DATA ENCODE/DECODE

function code_hex($data, $dir) {
	$s = '';
	if ($dir == "decode") {
		$data = str_replace('/','',$data);
		$data = str_replace(' ','',$data);
		$data = str_replace('\n','',$data);
		$data = explode(',',$data);
		foreach ($data as $c) {
			if (!$c) continue;
			$s .= chr($c);
		}
		return $s;
	}
	$n = strlen($data);
	for ($i = 0; $i < $n; $i++) {
		
	}
	return urlencode($data);
}

function code_url($data, $dir) {
	if ($dir == "decode") return urldecode($data);
	return urlencode($data);
}
# NTS sometime return binary data get dont show up in browser
function code_64($data, $dir) {
	if ($dir == "decode") return base64_decode($data);
	return base64_encode($data);
}
function code_img64($data, $dir) {
	if ($dir == "decode") return "can only encode";
	if (!is_file($data)) return "file not found";
	$type = strpos($data,'.'); if ($type === false) return "no file type";
	$type = substr($data,$type);
	$data = file_get_contents($data);
	$data = base64_encode($data);
	return "\"data:image/$type;base64,".$data.'"';
}
function code_json($data, $dir) {
	if ($dir == "decode") {
		$s = var_export(json_decode($data),true);
		// probably not perfect but seems good enough...
		$s = str_replace("stdClass::__set_state(","",$s);
		$s = str_replace("))",")",$s);
		return "$s;";
	}
# NOTE $data MUST be like:
#      return array("see PHP json_encode() example");
	return json_encode(eval($data));
}

// Google hides links (search results and gmail) in a "&url=" among other 
// crap and THAT means that THEY get all your clicks first... This is to copy, 
// paste, "decode" to clean the link. (One can do that manually, I know.)
function code_gurl($data, $dir) {
	if ($dir == "encode") return "can only decode";
	$r = preg_match('/&url=(.*)&/U',$data,$res);
	if ($r) return urldecode($res[1]);
	return "";
}

//
function code_exec($data, $dir, $args) {
	file_put_contents("dat.tmp",$data);
	$cmd = "$args dat.tmp";
	$r = codeexec($cmd);
	unlink("dat.tmp");
	return $r;
}

function code_sekret($data, $dir) {
	$id = 'ID';
	$style = 0;
//	if ($dir == "encode") {
	$css = '';
	$n = strlen($data);
	for ($i = 0; $i < $n; $i++) {
		$css .= '\\'.bin2hex($data[$i]);
	}
	if ($id) {
		$css = "#$id:before{content:\"$css\"}";
	}
	if ($style) {
		$css = "<style>$css</style>";
	}
	return $css;
}

// more here later
// users add similar functions here (or whereever)

// other functions

/* codeexec - common execute a program function */
function codeexec($cmd) {
	$cmd .= " 2>err.txt";
	exec($cmd,$out,$ret);
	$result = implode("\n",$out);
	if ($ret)
		$result .= "\nreturn: $ret\n";
	if (file_exists("err.txt") && filesize("err.txt")) {
		$result .= file_get_contents("err.txt");
		unlink("err.txt");
	}
	return $result;
}

// support functions

// "\\n" => "\n" etc.
function un_escape($s) {
	$s = 
	preg_replace(
	array('/(?<!\\\\)\\\\n/','/(?<!\\\\)\\\\r/','/(?<!\\\\)\\\\t/'),
	array("\n","\r","\t"),
	$s
	);

	$s = str_replace(
	array('\\\\n','\\\\r','\\\\t'),
	array('\n','\r','\t'),
	$s
	);

	return $s;
}

// print result
function print_out($res,$html) {
	print "<section>";
	if ($res && !is_string($res))
		$res = print_r($res,true);
	if ($GLOBALS['dump']) {
		echo "result: <br>";
		var_dump($res);
	} else
	if ($html) {
		print($res);
	} else {
		print "<pre>\n";
		print htmlentities($res);
		print "\n</pre>";
	}
	print "</section>\n";
}

// form support; print "checked" if set and equals or if just set
function c($n, $v = '') {
	if ($v) {
		if ($n == $v) {
			return 'checked';
		}
	}
	elseif ($n) {
		return 'checked';
	}
	return '';
}

// radio list of tmp files (all regardless of extenstion)
function tmp() {
	$s = "";
	foreach (glob("tmp.*") as $f) {
		if (strstr($f,".htm")) continue;
		$s .= "<input type='radio' name='import' value='$f'>$f ";
	}
	if ($s == "") $s = "(none found)";
	return $s;
}

function errorhand($errno, $errstr, $errfile, $errline) {
global $error;
	$error = (($errno == E_NOTICE) ? "Notice: " : "Warning: ") . $errstr;
	$error .= " line: $errline";
}

/*
   NOTEF

   Outside the TEXTAREA the FORM can submitted on Enter; or decode/encode. 

   The code blocks should be functions (i.e. an API).

   NOTED

   The $data blocks should be functionized as that is sloppy...


$ whereis python
python: /usr/bin/python /usr/bin/python3.6 /usr/bin/python3.7 /usr/lib/python2.7 /usr/lib/python3.6 /usr/lib/python3.7 /usr/lib/python3.8 /usr/local/lib/python3.8 /usr/include/python2.7 /usr/include/python3.6m /usr/include/python3.7m /usr/include/python3.8 /cygdrive/c/bin/python.bat /usr/src/python38-3.8.3-1.src/python3.cygport

Whay are there so many Pythons on Cygwin? Old software that has not been 
updated!

*/

/*
   Change Log

   v1.1.0
   Cleaned up; better documentation; added Ruby, Python.

   v1.0.4
   Added Rakudo support.

   v1.0.3

   Fixed stupid eval() error check.
   Added error_handler; display of error message.

   v1.0.2

   Added "below" code.
   Added test for PHP eval() error and to not htmlentitieize the output.

   v1.0.1

   Added "--" around output area.
   Added better calculation of 'GOEXEC'; cleaned up code_go().

   v1.0.0

   Added code execution for Go, Perl and Bash.
   Added import temporary code files.
   Re-designed HTML form for more "obviousness".

*/

// END