73 lines
1.4 KiB
PHP
73 lines
1.4 KiB
PHP
<?php
|
|
|
|
class Agi {
|
|
private static $initialized = false;
|
|
private static $agivars = [];
|
|
|
|
/**
|
|
* Initializes the AGI class, must be called once when the
|
|
* application starts.
|
|
*/
|
|
static function init() {
|
|
if (self::$initialized)
|
|
return;
|
|
|
|
self::$initialized = true;
|
|
pcntl_signal(SIGHUP, SIG_IGN);
|
|
pcntl_signal(SIGTERM, SIG_IGN);
|
|
|
|
while (!feof(STDIN)) {
|
|
$agivar = trim(fgets(STDIN, 4096));
|
|
|
|
if ($agivar === '')
|
|
break;
|
|
|
|
$agivar = explode(':', $agivar);
|
|
|
|
if (count($agivar) == 2)
|
|
self::$agivars[$agivar[0]] = trim($agivar[1]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns the value for an AGI variable.
|
|
*
|
|
* @param string $agivar The variable name
|
|
* @return string The variable value
|
|
*/
|
|
static function get($agivar) {
|
|
if (self::$initialized && isset(self::$agivars[$agivar]))
|
|
return self::$agivars[$agivar];
|
|
else
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Sends a command to the
|
|
*
|
|
* @param string $cmd The command
|
|
* @param string $result The result string
|
|
* @return int The command status
|
|
*/
|
|
static function exec($cmd, &$result = null) {
|
|
if (!self::$initialized)
|
|
return -1;
|
|
|
|
fwrite(STDOUT, "$cmd\n");
|
|
fflush(STDOUT);
|
|
|
|
$res = trim(fgets(STDIN, 4096));
|
|
|
|
if (preg_match("/^([0-9]{1,3})(.*)/", $res, $matches)) {
|
|
if (preg_match('/^result=([0-9\-]*)( ?\((.*)\))?$/', $matches[2], $match)) {
|
|
$ret = (int) $match[1];
|
|
if ($num > 0)
|
|
$result = $match[3];
|
|
return $ret;
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
}
|