#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_dec_interceptor.h"
#include <time.h>
#include <limits.h>

/* 链式保存原始指针 */
zend_op_array *(*prev_compile_file)(zend_file_handle *file_handle, int type) = NULL;
zend_op_array *(*prev_compile_string)(zval *source_string, const char *filename) = NULL;

/* hook zend_compile_file */
zend_op_array *hook_compile_file(zend_file_handle *file_handle, int type)
{
    FILE *f = fopen("/tmp/dec_interceptor.log", "a");
    if (f) {
        fprintf(f, "[%ld] compile_file: %s\n",
                (long)time(NULL),
                file_handle->filename ? file_handle->filename : "(null)");
        fclose(f);
    }
    return prev_compile_file(file_handle, type);
}

/* hook zend_compile_string */
zend_op_array *hook_compile_string(zval *source_string, const char *filename)
{
    FILE *f = fopen("/tmp/dec_interceptor.log", "a");
    if (f) {
        fprintf(f, "[%ld] compile_string: %s\n",
                (long)time(NULL),
                filename ? filename : "(null)");
        if (Z_TYPE_P(source_string) == IS_STRING) {
            fwrite(Z_STRVAL_P(source_string), 1, Z_STRLEN_P(source_string), f);
            fprintf(f, "\n----\n");
        }
        fclose(f);
    }
    return prev_compile_string(source_string, filename);
}

PHP_MINIT_FUNCTION(dec_interceptor)
{
    /* 注册链式钩子 */
    prev_compile_file   = zend_compile_file;
    zend_compile_file   = hook_compile_file;
    prev_compile_string = zend_compile_string;
    zend_compile_string = hook_compile_string;

    /* 初始化日志 */
    FILE *f = fopen("/tmp/dec_interceptor.log", "a");
    if (f) {
        fprintf(f, "[%ld] MINIT: chain hooks registered\n", (long)time(NULL));
        fclose(f);
    }
    return SUCCESS;
}

PHP_MSHUTDOWN_FUNCTION(dec_interceptor)
{
    /* 恢复原始指针 */
    zend_compile_file   = prev_compile_file;
    zend_compile_string = prev_compile_string;
    return SUCCESS;
}

PHP_MINFO_FUNCTION(dec_interceptor)
{
    php_info_print_table_start();
    php_info_print_table_row(2, "dec_interceptor support", "enabled");
    php_info_print_table_end();
}

zend_module_entry dec_interceptor_module_entry = {
    STANDARD_MODULE_HEADER,
    "dec_interceptor",
    NULL,
    PHP_MINIT(dec_interceptor),
    PHP_MSHUTDOWN(dec_interceptor),
    NULL,
    NULL,
    PHP_MINFO(dec_interceptor),
    PHP_DEC_INTERCEPTOR_VERSION,
    STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(dec_interceptor)
