Skip to content

Instantly share code, notes, and snippets.

@pqlx
Last active November 3, 2018 21:47
Show Gist options
  • Save pqlx/002cf1208ba6a208494349a91245de79 to your computer and use it in GitHub Desktop.
Save pqlx/002cf1208ba6a208494349a91245de79 to your computer and use it in GitHub Desktop.
hook functions in php
<?php
/*
Dirty hacks to not get into an infinite recusion when using
*/
foreach(
["file_put_contents",
"debug_backtrace",
"func_get_args",
"call_user_func_array"] as $safe)
{
runkit_function_copy($safe, $safe . "_safe");
}
function hook_log($function_name, $bt, $args, $bt_offset=2, $logging_constraints=false)
{
if($logging_constraints && !$logging_constraints($bt, $args))
{
return;
}
$pwd = realpath(dirname(__FILE__)) . '/';
$result = '';
$result .= strftime("%d/%b/%Y %H:%M:%S:") . "\n";
for($i = count($bt)-1 ; $i >= $bt_offset; --$i)
{
$curr = $bt[$i];
if(isset($curr['file']))
{
$file = $curr['file'];
$file = str_replace($pwd, '', $file);
$result .= "$file:{$curr['line']} ";
}
$result .= "in {$curr['function']}():\n";
if($i == $bt_offset)
{
$result .= "With args: " . var_export($args, true) . "\n";
}
elseif(isset($curr['args']))
{
$result .= "With args: " . var_export($curr['args'], true) . "\n";
}
}
$result .= "\n-------------------------------------------------------------------------------------------\n";
file_put_contents_safe("./calls/{$function_name}_calls.txt", $result, FILE_APPEND);
}
function create_hook($function_name, $log_constraints=false)
{
runkit_function_copy($function_name, $function_name . '_internal');
runkit_function_add($function_name . '_hook',
function() use ($function_name, $log_constraints) {
hook_log($function_name, debug_backtrace_safe(6), func_get_args_safe(), 2, $log_constraints);
return call_user_func_array_safe("{$function_name}_internal", func_get_args_safe());
});
runkit_function_redefine($function_name, '', "return call_user_func_array_safe('{$function_name}_hook',(func_get_args_safe()));");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment