<?php
header( 'content-type: text/plain' );

# General config:
$scriptFile             = 'executeAlone.php';
$storageDir             = __DIR__ . '/executeStorage';
$stripFirstPhpOpenLine  = true; # delete the first Line in $scriptFile('<?php ...'). (shold bee true)
                                # It is saver to use this, if executeAlone.php ($scriptFile) is callable via httpd.
# Config: a row of system-vars
if ( isset( $_ENV ) ) {
    $executeExportVars['_ENV'] = true;
}
$executeExportVars['_SERVER']  = true;
$executeExportVars['_GET']     = true;
$executeExportVars['_POST']    = true;
$executeExportVars['_COOKIE']  = true;
$executeExportVars['_SESSION'] = true;

# Config: examples for other vars: 
$executeExportVars['foo'] = true; $foo='FOO';
$executeExportVars['bar'] = true; $bar='BAR';
$_POST['mailto'] = 'fastix';

# The skript-interpreter (php or hhvm with path)
$phpBinary = '/usr/bin/php';
#$phpBinary = '/etc/alternatives/php';
#$phpBinary = '/usr/bin/hhvm'; # alternativ for the "hip hop virtual machine"


# Program:

if ( PHP_SESSION_ACTIVE != session_status() ) {
    session_start();
}
$_SESSION['id']   = session_id();
$_SESSION['test'] = 'Test';

$script = "<?php\n";

foreach ( $executeExportVars as $key => $value ) {
    if ( isset( $$key ) && $value ) {
        $var = $$key;
        echo "$$key wird exportiert: PHP: var_export( $$key, true )\n";
        $script .= '$' . "$key = " . var_export( $var, true ) . ";\n\n";
    }
}


if ( $stripFirstPhpOpenLine ) {
    $flag = ( ! $stripFirstPhpOpenLine );
    $rows = file( $scriptFile );
    foreach ( $rows as $row ) {
        if ( ! $flag ) {
            $flag = true;
        } else {
            $script .= $row;
        }
    }
} else {
    $script .= file_get_contents( $scriptFile );
}


$scriptName = tempnam( $storageDir, 'php_' );
file_put_contents( $scriptName, $script );

$errorFile = tempnam( $storageDir, 'error_' );
$command = "echo 'export MAIL=\"\" && $phpBinary $scriptName;' | batch 2> $errorFile; echo $?";

$return = 0;
$return = `$command`;

if ( 0 == $return ) {
    echo "Der Job '$phpBinary $scriptName' wurde erfolgreich in die Queue gestellt und wird ausgeführt sobald die Prozessorlast unter 80% liegt. (Meistens: sofort)\n";
    unlink( $errorFile );
} else {
    $error = file_get_contents( $errorFile );
    unlink( $errorFile );
    trigger_error( $error, E_USER_ERROR );
}