Eval'ing Plugins System - php

What would be the best way to do this?
I'm given a template with some things in it like {:HELLO-WORLD:} tags in it.
I'm also given an array like:
Array
(
[0] => Array
(
[Name] => {:HELLO-WORLD:}
[Plugin] => "<?php return 'Hello World'; ?>"
[Settings] =>
)
)
What can I do to make sure {:HELLO-WORLD:} gets replaced with the output of Hello World?
I am currently attempting:
private function PluginReplacer($arr, $str){
$gsCt = count($arr);
$kv = array();
for ($i=0;$i<$gsCt;++$i){
$kv[$arr[$i]['Name']] = $arr[$i]['Plugin'];
}
return str_replace(array_keys($kv), $this->EvalCode(array_values($kv)), $str);
}
// Eval Some Code
private function EvalCode($var){
require_once('plugins.php');
$pr = new CloudCMSPluginRunner();
$pr->Code = $var;
$pr->SitePath = GetSiteAssetsPath($this->SiteID);
$pr->RunIt();
echo $pr->Error;
}
<?php
class CloudCMSPluginRunner {
public $Code = '';
public $Error = '';
public $SitePath = '';
private $DoNotAllow = array('echo', 'eval', 'phpinfo', '/`/', 'chmod', 'chown', 'umask', 'shell_exec',
'exec', 'escapeshellcmd', 'proc_open', 'proc_terminate', 'proc_get_status',
'passthru', 'proc_nice', 'system', 'escapeshellarg', 'ob_start', 'ob_end_clean',
'ob_get_clean', 'session_start', 'putenv', 'header', 'sleep', 'uwait', 'ini_set',
'error_reporting', 'chgrp', 'basename', 'clearstatcache', 'copy', 'delete',
'dirname', 'disk_free_space', 'disk_total_space', 'diskfreespace', 'fclose',
'feof', 'fflush', 'fgetc', 'fgetcsv', 'fgets', 'fgetss', 'file_exists', 'file_get_contents',
'file_put_contents', 'file', 'fileatime', 'filectime', 'filegroup', 'fileinode', 'filemtime',
'fileowner', 'fileperms', 'filesize', 'filetype', 'flock', 'fnmatch', 'fopen', 'fpassthru',
'fputcsv', 'fputs', 'fread', 'fscanf', 'fseek', 'fstat', 'ftell', 'ftruncate', 'fwrite', 'glob',
'is_dir', 'is_executable', 'is_file', 'is_link', 'is_readable', 'is_uploaded_file', 'is_writeable',
'is_writable', 'lchgrp', 'lchown', 'link', 'linkinfo', 'lstat', 'mkdir', 'move_uploaded_file',
'parse_ini_file', 'parse_ini_string', 'pathinfo', 'pclose', 'popen', 'readfile', 'readlink',
'realpath_cache_get', 'realpath_cache_size', 'realpath', 'rename', 'rewind', 'rmdir', 'set_file_buffer',
'stat', 'symlink', 'tempnam', 'tmpfile', 'touch', 'unlink', 'chdir', 'chroot', 'closedir', 'dir',
'getcwd', 'opendir', 'readdir', 'rewinddir', 'scandir', 'dio_close', 'dio_fcntl', 'dio_open', 'dio_read',
'dio_seek', 'dio_stat', 'dio_tcsetattr', 'dio_truncate', 'dio_write', 'finfo_buffer', 'finfo_close',
'finfo_file', 'finfo_open', 'finfo_set_flags', 'mime_content_type', 'inotify_add_watch', 'inotify_init',
'inotify_queue_len', 'inotify_read', 'inotify_rm_watch', 'setproctitle', 'setthreadtitle', 'xattr_get',
'xattr_list', 'xattr_remove', 'xattr_set', 'xattr_supported');
public function RunIt(){
$valid = $this->CheckIt();
if($valid){
eval($this->Code);
}else{
// code is invalid
$this->Error = 'The code in this plugin is invalid.';
return null;
}
}
private function CheckIt(){
$ret = false;
ob_start(); // Catch potential parse error messages
$code = eval('if(0){' . "\n" . $this->Code . "\n" . '}');
ob_end_clean();
$ret = ($code !== false);
// run a check against the dissallowed
$ret = (stripos($this->Code , $this->DoNotAllow) !== false);
// make sure any path is there's and there's alone
$ret = (stripos($this->Code , $this->SitePath) !== false);
return $ret;
}
}
?>
But nothing is happenning... in fact the page I am attempting to run this on blanks out (meaning there is an error happenning)

You're generating code formatted as:
eval("function GetPageWeAreOn(){$p=explode('/',$_SERVER['REQUEST_URI']);return $p[1];}");
What's happening is that PHP is interpreting the variables wrongly - instead of passing them in to the eval'ed function, it's interpolating them first.
I've avoided the error by escaping them:
eval("function GetPageWeAreOn(){\$p=explode('/',\$_SERVER['REQUEST_URI']);return \$p[1];}");
You can avoid the need for escaping by putting your string to be eval'ed into single quotes, too - that doesn't try to interpolate variables:
eval('function GetPageWeAreOn(){$p=explode("/",$_SERVER["REQUEST_URI"]);return $p[1];}');

Related

How can I decode php code that using goto statement?

I have several large files as below:
public function index()
{
goto E9e2246508a1d047;
b59f99a7185ea4f4:
return View("\x65\155\160\154\x6f\171\x65\162\56\x74\x72\x61\156\163\141\x63\x74\x69\x6f\156\x73", ["\x70\x61\147\x65" => $F44ac1942f77c961]);
goto b4ef380f386bfff0;
E021694d1d524d6a:
$F44ac1942f77c961 = $C52f2627c8748472->lastpage();
goto b59f99a7185ea4f4;
E9e2246508a1d047:
$C52f2627c8748472 = UserTransaction::where("\165\x73\145\162\x5f\x69\x64", Auth::id())->orderBy("\143\x72\x65\141\164\x65\x64\x5f\141\x74", "\x61\163\x63")->paginate(10);
goto E021694d1d524d6a;
b4ef380f386bfff0:
}
From UnPHP - The Online PHP Decoder I decode it to :
public function index()
{
goto E9e2246508a1d047;
b59f99a7185ea4f4:
return View("employer.transactions", ["page" => $F44ac1942f77c961]);
goto b4ef380f386bfff0;
E021694d1d524d6a:
$F44ac1942f77c961 = $C52f2627c8748472->lastpage();
goto b59f99a7185ea4f4;
E9e2246508a1d047:
$C52f2627c8748472 = UserTransaction::where("user_id", Auth::id())->orderBy("created_at", "asc")->paginate(10);
goto E021694d1d524d6a;
b4ef380f386bfff0:
}
The name of the variables is not very important to me (Though it's better to be true).
But I want to delete goto command and have a clean code.
Rewrite the code with gotos:
public function index()
{
goto E9e2246508a1d047;
E9e2246508a1d047:
$C52f2627c8748472 = UserTransaction::where("user_id", Auth::id())->orderBy("created_at", "asc")->paginate(10);
goto E021694d1d524d6a;
E021694d1d524d6a:
$F44ac1942f77c961 = $C52f2627c8748472->lastpage();
goto b59f99a7185ea4f4;
b59f99a7185ea4f4:
return View("employer.transactions", ["page" => $F44ac1942f77c961]);
goto b4ef380f386bfff0;
b4ef380f386bfff0:
}
Then delete them:
public function index()
{
$C52f2627c8748472 = UserTransaction::where("user_id", Auth::id())->orderBy("created_at", "asc")->paginate(10);
$F44ac1942f77c961 = $C52f2627c8748472->lastpage();
return View("employer.transactions", ["page" => $F44ac1942f77c961]);
}
here is my solution after passing the code through the parser from your provided url:
$result = $source; // source code
$goto = []; // collect all goto blocks to remove them after
$result = preg_replace_callback('/goto (\w+);*/', function($m) use ($source, &$goto) {
$goto[] = $m[1].':';
preg_match("/{$m[1]} *:(((?!goto).)*)/s", $source, $m);
return $m[1];
}, $source);
$result = str_replace($goto, '', $result); // replace goto:
$result = preg_replace('/([\r\n])+\s+/', "\n", $result);
// view the result
echo '<pre>';
echo htmlentities($result);
echo '</pre>';die();

showing my models value on view in codeigniter

im new in codeigniter and get some trouble with my function
here is my model
public function kode_unik(){
$q = $this->db->query("select MAX(RIGHT(id_obat,5)) as code_max from obat");
$code = "";
if($q->num_rows()>0){
foreach($q->result() as $cd){
$tmp = ((int)$cd->code_max)+1;
$hitung = strlen($tmp);
if ($hitung == 1 ){
$a = "0000".$tmp;
} elseif ($hitung == 2) {
$a = "000".$tmp;
}elseif ($hitung == 3) {
$a = "00".$tmp;
}elseif ($hitung == 4) {
$a = "0".$tmp;
}else{
$a = $tmp;
}
$code = sprintf("%s", $a);
}
}else{
$code = "0001";
}
$kodenyami = "E".$code;
return $kodenyami;
}
and then i wanna get the result of my models to show in my view.
here is my controller
public function add_data()
{
$this->load->helper( array('fungsidate', 'rupiah', 'url') );
$this->load->model('obat');
$this->load->database();
$data['a'] = $this->obat->tampil_data();
$data['b'] = $this->obat->kode_unik();
$componen = array(
"header" => $this->load->view("admin/header", array(), true),
"sidebar" => $this->load->view("admin/sidebar", array(), true),
"content" => $this->load->view("admin/add_obat", array("data" => $data), true)
);
$this->load->view('admin/index', $componen);
}
and my view goes here.
<i class="fa fa-medkit fa-5x"></i></div>
<div class="col-xs-9 text-right">
line20-> <div class="huge"><?php echo $b; ?></div>
<div>ID Obat</div>
the code give me an errors Message: Undefined variable: b
just don't know how to put the value of my models $kode_unik into my view ..
thanks
$data is already an array. Maybe like this :
"content" => $this->load->view("admin/add_obat", $data, TRUE)
CodeIgniter will extract the keys in $data so you will be able to use them in your view as $b
BTW instead of passing array() as a parameter of the load->view you can use NULL
P.S If you set the last parameter to TRUE, you will return the populated content of that view as a String (HTML in that case)
Here is something to start with :
public function __construct() {
parent::construct();
$this->load->helper(‘array(‘fungsidate’, ‘rupiah’, ‘url’);
$this->load->model(‘obat’);
$this->load->database(); // Should be already loaded depending on your config
}
public function add_data() {
// Set the data
$data[‘a’] = $this->obat->tampil_data();
$data[‘b’] = $this->obat->kodeunik();
// Load the views
$componen = array(
‘header’ => $this->load->view(‘admin/header’, NULL, TRUE);
‘sidebar’ => $this->load->view(‘admin/sidebar’, NULL, TRUE);
‘content’ => $this->load->view(‘admin/add_obat', $data, TRUE);
);
$this->load->view(‘admin/index’ ,$componen);
}
From what I understand about your code, in your templates you will need to echo the array keys
in admin/header you will echo $header;
in admin/sidebar you will echo $sidebar;
in admin/add_obat you will need to echo $content
and then you admin/index should be populated. I won’t do that if I were you to be honest I would probably load each template as is instead of outputting them as HTML string inside the final index. I don’t know exactly how you did your structure so it’s kinda hard for me to guess well. But in my case I would have use something like this instead of the componen array
public function add_data() {
// Set the data
$data[‘a’] = $this->obat->tampil_data();
$data[‘b’] = $this->obat->kodeunik();
// Load the views
$this->load->view(‘admin/header’);
$this->load->view(‘admin/sidebar’);
$this->load->view(‘admin/add_obat, $data); // This should be the body template of your page
$this->load->view(‘admin/footer’); // I guess you have a footer template
}
I hope this will help you!

$session data returns only 0

I'm trying to put a script together that will do some math for the user.
That works fine however when i try to put it in a session and try to show the value to the user it will only return 0 if its set to 0.
Does anybody know where i did wrong?
<?php
session_start();
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$class1 = filter_var($_POST['class1'], FILTER_SANITIZE_STRING);
$class2 = filter_var($_POST['class2'], FILTER_SANITIZE_STRING);
$class3 = filter_var($_POST['class3'], FILTER_SANITIZE_STRING);
$class4 = filter_var($_POST['class4'], FILTER_SANITIZE_STRING);
$class5 = filter_var($_POST['class5'], FILTER_SANITIZE_STRING);
$class1C = $class1 * 35;
$class2C = $class2 * 5;
$class3C = $class3 * 7.5;
$class4C = $class4 * 26;
$class5C = $class5 * 2.5;
$totaal1 = $class1C + $class2C + $class3C + $class4C + $class5C;
$res = array($class1C, $class2C, $class3C, $class4C, $class5C, $totaal1);
foreach($res as $name => $var) {
$_SESSION[$name] = $var;
}
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<h3>Session information: var_dump($_SESSION[$class1C]) ($_SESSION[$class2C]) ($_SESSION[$totaal1])</h3>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error</h3>";
}
echo json_encode($result);
exit;
?>
You cannot call var_dump inside the double quoted string, and var_dump does not return anything: it only display things.
Even if you could, $class1C is not a valid index for $_SESSION
Keeping the same logic as your code, you may change your line to the following:
$result["html"] = "<h3>Session information:";
ob_start();
var_dump($_SESSION[0]); // contains $class1C
echo $_SESSION[1]; // contains $class2C
echo $_SESSION[5]; // contains $totaal1
$result["html"] .= ob_get_clean();
$result["html"] .= "</h3>";
EDIT:
If you want to use the indexes 'class2C', 'totaal1' etc.. you need to init $res as follow:
$res = array(
'class1C' => $class1C,
'class2C' => $class2C,
'class3C' => $class3C,
'class4C' => $class4C,
'class5C' => $class5C,
'totaal1' => $totaal1
);
Then, your loop to set $_SESSION will set correct indexes, and you will be able to use $_SESSION['class1C'] to get proper values.

Cant pass array value from codeigniter controller to view

Inside my controller, I have a line that needs to pass $content['pass_check'] to the view. It is inside an if statement that checks for validation. This I have found causes it to break. Once I move the $content['pass_check'] outside of any if statement, it works just fine passing to the view. All of the other values are passed (accounts, expense_accounts, vendors, terms). What must I do to get it to pass within this if statement. I've even tried moving it outside of the validation and it still wont set.
function create() {
require_permission("INVOICE_EDIT");
$this->load->library("form_validation");
$this->form_validation->set_rules("invoice_number", "Invoice Number", "required");
if($this->form_validation->run() !== false) {
$post = $this->input->post();
$this->session->set_userdata("create_invoice_vendor", $post['vendor_id']);
$this->session->set_userdata("create_invoice_date", $post['invoice_date']);
$invoice_number_exists = $this->invoices->count(array("invoice_number" => $post['invoice_number'])) > 0;
$post['invoice_date'] = date("Y-m-d", strtotime($post['invoice_date']));
$post['due_date'] = date("Y-m-d", strtotime($post['due_date']));
$post['date_entered'] = "now()";
$id = $this->invoices->insert_invoice($post);
$this->load->model("vendors");
if(isset($post['invoice_number'])){
$string_check= $post['invoice_number'];
$string_check= preg_replace('/\d/', '#', $string_check);
$string_check= preg_replace('/\w/', '#', $string_check);
$invoice_pattern=array();
$invoice_pattern = $this->db->select("invoice_pattern")->where("vendor_id",
$post['vendor_id'])->get("vendors")->result();
$invoice_pattern=$invoice_pattern[0]->invoice_pattern;
* //// THIS IS WHERE I NEED HELP ///////
if($invoice_pattern == $string_check){
***$content['post_check'] = 1;***
$this->invoices->flag_invoice($id);
};
};
$history = array(
"type" => "invoice_entered",
"comments" => "Invoice was entered",
"link" => $id,
"admin_id" => $this->user->admin_id,
"date" => "now()",
);
$this->vendors->insert_history($post['vendor_id'], $history);
if($post['flagged'] == 1) {
$this->invoices->flag_invoice($id);
}
if($invoice_number_exists) {
redirect("invoices/confirm_invoice/".$id);
} else {
// redirect("invoices/view/".$id);
redirect("invoices/create");
}
}
$content['accounts'] = $this->db->get("acct_chart_of_accounts")->result();
$content['expense_accounts'] = $this->db->get("invoice_expense_accounts")->result();
$content['vendors'] = $this->db->select("vendor_id, name, terms, override, invoice_pattern")
->order_by("name ASC")->get("vendors")->result();
$content['terms'] = $this->db->query("SELECT DISTINCT(terms) FROM vendors")->result();
}
}
$this->template['sub_heading'] = "Create";
$this->template['content'] = $this->load->view("invoices/create", $content, true);
$this->template['sidebar'] = $this->load->view("invoices/sidebar", array(), true);
$this->template['scripts'] = array("codeigniter/javascript/invoices/create.js");
$this->template['styles'][] = "codeigniter/styles/invoices/create.css";
$this->display();
}
Obviously it won't pass it to the view if the condition doesn't match, because you're only declaring the variable within the condition if it matches.
Just create $content['pass_check'] with an initial value of 0 or whatever before the conditional check first.
function create() {
...snip...
$content['pass_check'] = 0;
if($invoice_pattern == $string_check) {
$content['post_check'] = 1;
$this->invoices->flag_invoice($id);
};
...snip...
}
Let me know if this works or not please.

My iMacro script(s) doesnt run inside my PHP script. Why?

I am learning how to run iMacros from my php scripts so that PHP script calls an iMacros browser session and passes any variables that I have (url and macro name for example). The iMacros session then runs the iMacro, after the macro is done running it passes the resulting html page back to the PHP script and closes itself. In an ideal world, anyway.
Here is the iMacros calling script:
<?php
require 'src/iimfx.class.php';
$iim = new imacros();
$vars = array();
$iim->play($vars,'grab_data.iim');
?>
But when i run this script from cmd.exe [command line] on WAMP, I get this:
New imacros session started!
Using Proxy: MY_PROXY_IP:MY_PROXY_PORT
-runner -fx -fxProfile default
--------------------------------------------------------
Setting Value IP => MY_PROXY_IP
Setting Value port => MY_PROXY_PORT
Playing Macro proxy.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
--------------------------------------------------------
Playing Macro grab_google.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
P.S. MY_PROXY_IP and MY_PROXY_PORT are replaced with actual numbers both in error messages above and iimfx.class.php.
And here is code for the iimfx.class.php :
<?php
class imacros {
function __construct($proxyip = 'MY_PROXY_IP', $proxyport = 'MY_PROXY_PORT', $silent = false, $noexit = false) {
echo "--------------------------------------\nNew imacros session started!\nUsing Proxy: $proxyip:$proxyport\n";
$this->proxyip = $proxyip;
$this->proxyport = $proxyport;
if (empty ( $this->proxyip ))
echo "NO PROXY!!\n";
$this->noexit = $noexit;
$this->fso = new COM ( 'Scripting.FileSystemObject' );
$this->fso = NULL;
$this->iim = new COM ( "imacros" );
$toexec = "-runner -fx -fxProfile default";
if ($silent === true)
$toexec .= " -silent";
if ($noexit === true)
$toexec .= " -noexit";
echo $toexec . "\n";
$this->iim->iimInit ( $toexec );
if (! empty ( $this->proxyip )) {
$dvars ['IP'] = $this->proxyip;
$dvars ['port'] = $this->proxyport;
$this->play ( $dvars, 'proxy.iim' );
}
}
function __destruct() {
if ($this->noexit === false)
$this->iim->iimExit ();
}
function play($immvars = '', $macro) {
echo "--------------------------------------------------------\n";
if (is_array ( $immvars )) {
foreach ( $immvars as $key => $value ) {
echo "Setting Value $key => $value\n";
$this->iim->iimSet ( "-var_" . $key, $value );
}
}
echo "Playing Macro $macro\n";
$s = $this->iim->iimPlay ( $macro );
if($s>0){
echo "Macro successfully played!\n";
}else{
echo "--------MACRO ERROR!-------------------\n ERROR: " . $this->getLastError() . "\n";
}
return $s;
}
// This function retrieves extracts in your iMacros script if you have any.
function getLastExtract($num) {
return $this->iim->iimGetLastExtract ( $num );
}
// Returns the last error :)
function getLastError(){
return $this->iim->iimGetLastError();
}
// Enables/disables images
function setImages($images = 1) { // 1 = on 2 = off
$dvars ['images'] = $images;
$this->play ( $dvars, 'images.iim' );
}
// Enables or disables adblockplus
function enableABP($status = true){
$dvars['status'] = $status;
$this->play ( $dvars, 'abp.iim' );
}
}
?>
Is there something I am missing here?
I have iimRunner.exe running during all of this [started manually before running the script] and I have iMacros Browser V8+.
Also, my grab_data.iim and all other required .iim are in the same place as the php script that is trying to call them and execute them.
Any kind of help and/or steer towards the right direction would be greatly appreciated!!
Thanks in advance.
U must by start the immrunner, before start the script =)
http://wiki.imacros.net/iimRunner

Categories